c++ - 从字符串序列中提取最后 2 个单词,以空格分隔

标签 c++ algorithm string stl tokenize

我有任何序列(或句子),我想提取最后 2 个字符串。

例如,

  • sdfsdfds sdfs dfsd fgsd 3 dsfds 应该产生:3 dsfds
  • sdfsd (dfgdg)gfdg fg 6 gg 应该产生:6 gg

最佳答案

您可以使用 std::string::find_last_of查找空格的函数。

int main()
{
    std::string test = "sdfsdfds sdfs dfsd fgsd 3 dsfds";

    size_t found1 = test.find_last_of( " " );
    if ( found1 != string::npos ) {
        size_t found2 = test.find_last_of( " ", found1-1 );
        if ( found2 != string::npos ) 
            std::cout << test.substr(found2+1, found1-found2-1) << std::endl;
        std::cout << test.substr(found1+1) << std::endl;
    }

    return 0;
}

关于c++ - 从字符串序列中提取最后 2 个单词,以空格分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3875594/

相关文章:

c++ - 在没有事先声明的情况下错误使用枚举?

C++ 整数类型 : special meaning for certain values

java - 二维数组 - 错误的 "Wall "放置?

algorithm - 除了 Haar 级联之外,还有哪些算法或方法可用于自定义对象检测?

algorithm - "spacify"CamelCased 字符串的算法

javascript - 获取字符串中连字符后的数值

c++ - 如何将 double 转换为整数

c++ - g++:Ubuntu 发行版升级后,我的所有代码都不会链接

algorithm - 遍历编号完全树中寻找节点第i个子节点公式的直观推导

c# - string.ToLower() 和 string.ToLowerInvariant()