我有一个字符串,想要获取其中某个字符(例如最后一个".")的位置,但是到目前为止我只是感到头痛。
谢谢
string lastN(string input)
{
return input.substr(input.size() - n);
}
您是否需要使用find_last_of函数?
size_type find_last_of( const basic_string& str, size_type pos = npos ) const;
查找最后一个等于给定字符序列中任一字符的字符。搜索在pos处结束,即仅考虑[0,pos]子字符串。如果传递npos作为pos,则将搜索整个字符串。#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;
}
<stdio.h>
是非标准的。请使用<cstdio>
。<string.h>
同理。 - Chris Hopman #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) : "";
}