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?
The difference between substring() and substr()The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .
The substring() method extracts characters from start to end (exclusive). The substring() method does not change the original string. If start is greater than end, arguments are swapped: (4, 1) = (1, 4). Start or end values less than 0, are treated as 0.
Strings are actually one-dimensional array of characters terminated by a null character '\0'.
Implement substr() function in C The substr() function returns the substring of a given string between two given indices. It returns the substring of the source string starting at the position m and ending at position n-1 .
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
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/).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With