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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4455775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:27:41  来源:igfitidea点击:

c++ get the last (n) char in a string

c++string

提问by Castro Roy

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.

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

thanks

谢谢

回答by Kos

Is find_last_ofwhat you need?

find_last_of你需要什么?

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.

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

回答by take-it

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

回答by thbusch

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:

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

回答by user744951

   #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) : "";
    }