C++ 基于c+中的多个字符串分隔符拆分字符串+;
我正在用C++98编写代码,只使用标准库。 我正在尝试编写一些代码,将字符串拆分为多个子字符串,每个子字符串由字符串“OK”或字符串“ERROR”分隔。 每个子字符串都应该放在mysubstring数组中 这是我为单个分隔符编写的代码:C++ 基于c+中的多个字符串分隔符拆分字符串+;,c++,string,c++98,C++,String,C++98,我正在用C++98编写代码,只使用标准库。 我正在尝试编写一些代码,将字符串拆分为多个子字符串,每个子字符串由字符串“OK”或字符串“ERROR”分隔。 每个子字符串都应该放在mysubstring数组中 这是我为单个分隔符编写的代码: void split_string() { for (unsigned short k=0;k<10;k++) { mysubstring[k]=""; //resetting all substrings } stri
void split_string()
{
for (unsigned short k=0;k<10;k++)
{
mysubstring[k]=""; //resetting all substrings
}
string separator = "OK";
size_t pos = 0;
unsigned short index=0;
while ((pos = str_to_split.find(separator)) != std::string::npos) {
mysubstring[index] = str_to_split.substr(0, pos);
str_to_split.erase(0, pos + separator.length());
index++;
}
void split_string()
{
对于(无符号短k=0;k算出:
void split_string()
{
for (unsigned short k=0;k<10;k++)
{
mysubstring[k]=""; //resetting all substrings
}
string okseparator = "OK";
string koseparator = "ERROR";
size_t okpos = 0;
size_t kopos = 0;
unsigned short index=0;
while (1)
{
okpos = string_to_split.find(okseparator);
kopos = string_to_split.find(koseparator);
if (okpos < kopos)
{
mysubstring[index] = string_to_split.substr(0, okpos + okseparator.length());
string_to_split.erase(0, okpos + okseparator.length());
index++;
}
else if (okpos > kopos)
{
mysubstring[index] = string_to_split.substr(0, kopos);
string_to_split.erase(0, kopos + koseparator.length());
index++;
}
else
{
break;
}
}
}
void split_string()
{
for(无符号短k=0;k kopos)
{
mysubstring[index]=字符串\u到\u split.substr(0,kopos);
字符串_to_split.erase(0,kopos+koseparator.length());
索引++;
}
其他的
{
打破
}
}
}
我得到两个分离器的位置,但我只考虑最靠近的位置。
当两个分隔符的位置相同时,while(1)终止(string::npos=max(size\u t))。为什么不起作用?您希望它做什么?您看到的实际结果是什么?我想当okpos=kopos时,尤其是当okpos=max(size\u t)时,我看到一个无限循环=kopos。当string::find==nposHow发布一个我们可以实际测试的,而不仅仅是代码片段时会发生这种情况?当然,抱歉。添加了。
#include <iostream>
#include <string.h>
void split_string();
string str_to_split = "skdjfnsdjknfjk OK fkjsnfjksdnfjnsdjkfn ERROR skjdfnjksdnf OK sjkdnfjksdnfjERROR jnfjnsdjfnsjdknfjkn OK";
use namespace std;
int main()
{
split_string();
return 0;
}
void split_string()
{
for (unsigned short k=0;k<10;k++)
{
mysubstring[k]=""; //resetting all substrings
}
string okseparator = "OK";
string koseparator = "ERROR";
size_t okpos = 0;
size_t kopos = 0;
unsigned short index=0;
while (1)
{
okpos = string_to_split.find(okseparator);
kopos = string_to_split.find(koseparator);
if (okpos < kopos)
{
mysubstring[index] = string_to_split.substr(0, okpos + okseparator.length());
string_to_split.erase(0, okpos + okseparator.length());
index++;
}
else if (okpos > kopos)
{
mysubstring[index] = string_to_split.substr(0, kopos);
string_to_split.erase(0, kopos + koseparator.length());
index++;
}
else
{
break;
}
}
}