c ++获取字符串中的最后一个(n)字符

时间:2010-12-15 22:51:50

标签: c++ string

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

感谢

4 个答案:

答案 0 :(得分:9)

find_last_of你需要什么?

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

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

答案 1 :(得分:6)

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

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

答案 2 :(得分:5)

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

答案 3 :(得分:1)

   #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) : "";
    }
相关问题