14

I would like to use substr() function in order to get the chain of characters from the 1. to the last, without 0. Should I do sth like this: string str = xyz.substr(1, xyz.length()); or (xyz.length() - 1) ? And why?

whatfor
  • 333
  • 2
  • 3
  • 7

4 Answers4

24

You don't need to specify the number of character to include. So as I said in my comment:

string str = xyz.substr(1)

This will return all characters until the end of the string

Community
  • 1
  • 1
styvane
  • 59,869
  • 19
  • 150
  • 156
9

The signature for substr is

string substr (size_t pos = 0, size_t len = npos) const;

As the length of the new string is 1 less than the old string you should call it as follows:

string str = xyz.substr(1, xyz.length() - 1);

You can actually omit the second argument as it defaults to string::npos. "A value of string::npos indicates all characters until the end of the string." (see http://www.cplusplus.com/reference/string/string/substr/).

RJinman
  • 603
  • 4
  • 15
4

The both declarations

std::string str = xyz.substr( 1, xyz.length() ); 

and

std::string str = xyz.substr( 1, xyz.length() - 1 );

are valid (though the first one can confuse the reader of the code) provided that the size of str is not equal to 0.

However this declaration

std::string str = xyz.substr( 1 );

is more expressive.

If string xyz can be an empty string then you should write something like

std::string str = xyz.substr( !xyz.empty() ? 1 : 0 );

or

std::string str = xyz.substr( xyz.size() != 0 ? 1 : 0 );
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • @user3100115 They all need to determine the length, but it's stored not computed so not really an issue. (`string::size()` is required to be O(1).) – Alan Stokes Jan 09 '16 at 22:14
0

If you want to find the sub string of string starting from a certain index till the end of the string, you can do the following.

char * substring(char *s){
    return s;
 }

 int main(){
char s[1][n]; // suppose we just take a single string.
char *sub;

scanf("%s",s[1]);            //s[1]="ababaaa"

sub=substring(s[1]+1);      //sub="babaaa"(starting from 1st index).
sub=substring(s[1]+3);      //sub="baaa" (starting from 3rd index).

return 0;
}
Suvab
  • 41
  • 1
  • 5