i have a string and i want to get, for example, the position of the last (.) in the string, or whatever char i want to check, but untill now i just get a headeach.
thanks
i have a string and i want to get, for example, the position of the last (.) in the string, or whatever char i want to check, but untill now i just get a headeach.
thanks
string lastN(string input)
{
return input.substr(input.size() - n);
}
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 characters in the given character sequence. Search finishes at pos, i.e. only the substring [0, pos] is considered in the search. If npos is passed as pos whole string will be searched.
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 a 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;
}
<stdio.h>
is nonstandard. Use <cstdio>
. Same for <string.h>
.
Commented
Dec 15, 2010 at 23:59
#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) : "";
}