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