当字符串中只有一个"GOOD"字符串可用时,从没有空格的字符串中提取第一个单词的最佳和有效方法?

Best and efficient way to extract a First word from string without space when only a "GOOD" string is available in string?

本文关键字:字符串 单词 第一个 最佳 提取 有效 方法 空格 GOOD 有一个      更新时间:2023-10-16

当 std::string 中只有"GOOD">字符串可用时,从没有空格的字符串中提取第一个单词的最佳和有效方法是什么

std::string temp =" 这是我的堆栈流第二个问题好吗" 输出:这

当只有"好好">可用时,我的以下逻辑失败

#define SerachGOOD "GOOD"
#define SerachBAD "BAD "
#define firstpos 0
using namespace std;
void   removeSpaces(std::string & input)
{
input.erase(std::remove(input.begin(),input.end(),' '),input.end());
cout<<input<<endl;
}
void GetFirstiWord_IF_GOOD(std::string temp)
{
if (temp.find(SerachGOOD)  != std::string::npos)
{
std::string FirstWord = temp.substr(firstpos, temp.find(SerachGOOD));
removeSpaces(FirstWord);
cout<<FirstWord<<endl;
}
}

您的代码根本没有尝试提取第一个单词。 它只是从输入中删除所有空格,然后按原样返回剩余的输入。

因此,此输入:

" THIS IS MY STACK OVER FLOW SECOND QUESTION IS IT GOOD"

将输出以下内容:

"THISISMYSTACKOVERFLOWSECONDQUESTIONISITGOOD"

这不是你想要的。

尝试更多类似的东西:

#include <iostream>
#include <string>
#define SearchGOOD "GOOD"
void GetFirstWord_IF_GOOD(const std::string &temp)
{
if (temp.find(SearchGOOD) != std::string::npos)
{
std::string::size_type start_pos = temp.find_first_not_of(" t");
std::string::size_type end_pos = temp.find_first_of(" t", start_pos + 1);
if (end_pos == std::string::npos)
end_pos = temp.size();
std::string FirstWord = temp.substr(start_pos, end_pos - start_pos);
std::cout << FirstWord << std::endl;
}
}

或者更简单,让 STL 为您解析:

#include <iostream>
#include <string>
#include <sstream>
#define SearchGOOD "GOOD"
void GetFirstWord_IF_GOOD(const std::string &temp)
{
if (temp.find(SearchGOOD) != std::string::npos)
{
std::string FirstWord;
std::istringstream iss(temp);
iss >> FirstWord;
std::cout << FirstWord << std::endl;
}
}

使用std::stringstream读取字符串中的第一个单词。

std::string GetFirstiWord_IF_GOOD(std::string temp)
{
std::string FirstWord;
if (temp.find(SerachGOOD)  != std::string::npos)
{
std::stringstream ss(temp);
ss >> FirstWord;
}
return FirstWord;
}

演示

我注意到您的第一个字符串存在轻微异常,因为您有一个前导空格,这将引发一个简单的解析(在您的第二个示例的情况下,似乎可以正常工作,但在不同的字符串上会产生完全不同的结果(。

例如:"这是我的堆栈流第二个问题好吗">

VS:"这是我的堆栈流第二个问题好吗">

要解决此问题,请在第一个单词中添加初始偏移量,然后简单地将所有内容都移到第一个空格。 所以,找到,定位,然后拆分。

void GetFirstiWord_IF_GOOD(std::string temp)
{
while (isspace(temp[0])) {
temp.erase(0,1);
}
if (temp.find(SearchGOOD) != std::string::npos)
{
temp = temp.substr(0, temp.find_first_of(' '));
cout << temp << endl;
}
}

我认为您的删除字符串函数导致您在第一个字符串中取得了错误成功,但是我在系统上运行您的代码时遇到了麻烦。 如果您将上面的代码拖放到现有代码中,它应该按预期工作。