当字符串中只有一个"GOOD"字符串可用时,从没有空格的字符串中提取第一个单词的最佳和有效方法?
Best and efficient way to extract a First word from string without space when only a "GOOD" string is available in string?
当 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;
}
}
我认为您的删除字符串函数导致您在第一个字符串中取得了错误成功,但是我在系统上运行您的代码时遇到了麻烦。 如果您将上面的代码拖放到现有代码中,它应该按预期工作。
相关文章:
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- C++-字符串是否包含一个带有简单循环的单词
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 替换字符串中的单词,但忽略引号中的单词
- 替换字符串位置 X 中的单词C++
- 视觉C++使用 map 来比较字符串中的每个单词
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 输出返回编号。等于输入字符串的单词的字符串数
- 在字符串的每个单词的末尾插入字符串
- 分析字符串中的双精度和单词
- 如何使用运算符>>在自定义字符串中输入多个单词?
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- 字符串单词的唯一哈希值
- 使用std :: string ::比较(C )的字符串/单词操纵
- 如何比较字符串单词和聊天猜测
- 用C++计算文本文件中的相同字符串/单词