Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substr() from the 1. to the last character C++

Tags:

c++

string

substr

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?

like image 449
whatfor Avatar asked Jan 09 '16 20:01

whatfor


People also ask

Is substr () and substring () are same?

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 .

What is the use of substr () in string?

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.

What is the last character of a string in C?

Strings are actually one-dimensional array of characters terminated by a null character '\0'.

Is there a substr function in C?

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 .


2 Answers

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

like image 97
styvane Avatar answered Nov 09 '22 19:11

styvane


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/).

like image 29
RJinman Avatar answered Nov 09 '22 18:11

RJinman