C ++ get last (n) char in string

I have a string, and I want to get, for example, the position of the last (.) In the string or any other char that I want to check, but so far I just get headeach.

thanks

+4
source share
4 answers

Is find_last_of what you need?

size_type find_last_of( const basic_string& str, size_type pos = npos ) const; 

Finds the last character equal to one of the characters in the given character sequence. The search ends in pos, i.e. Only the substring [0, pos] is considered in the search. If npos is passed as pos, an entire string will be searched.

+8
source

If your string is a char array:

 #include <cstdio> #include <cstring> int main(int argc, char** argv) { char buf[32] = "my.little.example.string"; char* lastDot = strrchr(buf, '.'); printf("Position of last dot in string: %i", lastDot - buf); return 0; } 

.. or std :: string:

 #include <cstdio> #include <string> int main(int argc, char** argv) { std::string str = "my.little.example.string"; printf("Position of last dot in string: %i", str.find_last_of('.')); return 0; } 
+6
source
 string lastN(string input) { return input.substr(input.size() - n); } 
+5
source
  #include <string> /** * return the last n characters of a string, * unless n >= length of the input or n <= 0, in which case return "" */ string lastN(string input, int n) { int inputSize = input.size(); return (n > 0 && inputSize > n) ? input.substr(inputSize - n) : ""; } 
0
source

Source: https://habr.com/ru/post/1332279/


All Articles