我正在尝试通过以下方式在 C++ 中吐出一个字符串:
#include <bitset>
#include <iostream>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/timer.hpp>
using namespace std;
size_t const N = 10000000;
typedef string::const_iterator iter;
typedef boost::iterator_range<iter> string_view;
template<typename C>
void test_custom(string const& s, char const* d, C& ret)
{
C output;
bitset<255> delims;
while (*d)
{
unsigned char code = *d++;
delims[code] = true;
}
typedef string::const_iterator iter;
iter beg;
bool in_token = false;
bool go = false;
for (string::const_iterator it = s.begin(), end = s.end(); it != end; ++it)
{
if (delims[*it])
{
if (in_token)
{
output.push_back(typename C::value_type(beg, it));
in_token = false;
}
}
else if (!in_token)
{
beg = it;
in_token = true;
}
else
{
if (!go)
{
cout << typename C::value_type(beg, it);
//outputs the first character
go = true;
}
}
}
if (in_token)
output.push_back(typename C::value_type(beg, s.end()));
output.swap(ret);
}
vector<string_view> split_string(string in, const char* delim = " ")
{
vector<string_view> vsv;
test_custom(in, delim, vsv);
return vsv;
}
int split()
{
string text = "123 456";
vector<string_view> vsv = split_string(text);
for (int i = 0; i < vsv.size(); i++)
cout << endl << vsv.at(i) << "|" << endl;
return 0;
}
这里的问题是第一个字符由于某种原因被删除了......返回的字符串是'23'和'456'但我希望它们是'123 ' 和 '456'
所以,第一个字符是' '而不是'1'
最佳答案
我不熟悉 boost::iterator_range
,但它确实听起来像一对迭代器。
如果是这样,那么在这段代码中:
vector<string_view> split_string(string in, const char* delim = " ")
{
vector<string_view> vsv;
test_custom(in, delim, vsv);
return vsv;
}
您返回的迭代器引用了一个名为 in
的本地 string
,该字符串在函数返回时已不复存在。
这是未定义的行为。
一个解决方法是通过引用传递该字符串。
顺便说一下,一种在空白处拆分字符串的低效但简单且安全的方法是使用 istringstream
:
istringstream stream( source_string );
string word;
while( stream >> word ) { cout << word; }
免责声明:代码未经编译器处理。
关于C++ 字符串拆分错误(复杂方式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20447646/