C++ find 返回字符串变量 text 中的最后一个单词。字符串 getFirstWord(文本)

标签 c++

我试图转到字符串的末尾,返回直到最后一个空格,然后前进直到单词的末尾并将该单词存储在空字符串中。不允许使用数组或指针。

string getLastWord(string text)
{
    string lastword="";
    int last=text.size()- 1;
    int beginlast=0;
    if text == "";
    return  "";
    for (int i=last; i>=1; i--)
    {
        if (isspace(text[i]))
            beginlast=beginlast+i;
    }
    for (int k=0; k!=text.size; k++)
    {
        if (isalpha(text[k]))
            lastword=lastword+lastword[k];
    }
    return lastword;
}

最佳答案

你看过这个函数吗

string.find_last_of( ' ' );

编辑:好的,我看到现在有新的要求,试试这个(你应该做一些错误检查,比如如果你没有找到空格)

#include <iostream>
using namespace std;

int main() {
    string text{"my big and long string"};
    // find last space, counting from backwards
    int i = text.length() - 1; // last character
    while (i != 0 && !isspace(text[i]))
    {
      --i;
    }
    string lastword = text.substr(i+1); // +1 to skip leading space
    cout << lastword << endl;
    return 0;
}

关于C++ find 返回字符串变量 text 中的最后一个单词。字符串 getFirstWord(文本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7853686/

相关文章:

c++ - createInputLayout 返回 false

c++ - C str 表示 - const char* 与 const unsigned char*

c++ - 语法分解问题

c++ - 我如何在循环中再次设置变量

c++ - 使用 c++ 和 glfw 的 raii 架构

c++ - 当我运行C++程序时,它返回某种数字

c++ - 如何忽略以下编译器警告?

c++ - 如何判断函数是否可重入

c++ - 为什么实例member-fcn的cpp线程重置成员变量?

c++ - C++ 中堆栈、静态和堆内存的最大内存