C++获取字符串中的最后一个字符

问题描述:

我有一个字符串,我想获取,例如,字符串中最后一个(。)的位置,或者任何我想要检查的字符,但是现在直到现在我只是得到一个headeach。C++获取字符串中的最后一个字符

谢谢

+7

向我们展示你的代码为止。什么有效,你需要什么帮助? – abelenky 2010-12-15 22:53:44

+0

对不起,我迟到了,以回答您的意见,但我有一天所有的连接问题,多亏了所有的答案 – 2010-12-16 16:27:10

find_last_of你需要什么?

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

查找的最后一个字符等于在给定的字符序列的字符中的一个。搜索在pos完成,即在搜索中只考虑子串[0,pos]。如果npos作为pos传递,则将搜索整个字符串。

+0

这不是一个答案,这是一个猜测。 – 2010-12-15 22:54:39

+10

对我来说这似乎很不错。用这个问题猜测不了多少。 – 2010-12-15 23:03:22

+0

很好的链接,谢谢 – 2010-12-16 16:35:50

如果你的字符串是一个字符数组:

#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; 
} 

..或为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; 
} 
+1

''是非标准的。使用''。 ''也一样。 – 2010-12-15 23:59:45

+0

谢谢,纠正。 – thbusch 2010-12-16 08:52:11

string lastN(string input) 
{ 
    return input.substr(input.size() - n); 
} 
+0

N从哪里来? – karlphillip 2017-07-26 17:39:58

+0

这是不可接受的。 input.size()可能小于n。 – Pavel 2017-08-07 05:12:33