我有这个代码来分割一个字符串.出于某种原因,它只是坐在那里什么都不做.我不确定问题是什么.顺便说一下,delim = ' '在这里.
vector<string> split( const string &str, const char &delim )
{
typedef string::const_iterator iter;
iter beg = str.begin();
vector<string> tokens;
while(beg != str.end())
{
iter temp = find(beg, str.end(), delim);
if(beg != str.end())
tokens.push_back(string(beg, temp));
beg = temp;
}
return tokens;
}
Run Code Online (Sandbox Code Playgroud)
我可以为你调试它,我想但从长远来看这对你没有帮助.这是你做的.
在每一行之后,将printf()或cout staement转换为标准输出.然后运行您的代码,将一组简单的参数传递给它:
vector<string> x = split ("Hello there, Bob.", ' ');
Run Code Online (Sandbox Code Playgroud)
然后,检查输出以查看实现无效的原因.你可能不得不打破代码,因为如果它只是坐在那里,你可能会得到一个新的无限循环.
授人以鱼,他会吃了一天,授人以鱼,他永远不会再挨饿.
或者Terry Pratchett版本:
给男人一些火,他会一天是温暖的,立一个人的火,他会热情为他的余生.
更新:
既然你已经说过你已经完成了我的建议,这就是我从中做到的.很明显,当你设置beg到循环temp结束时while,它指向空间.这是通过beg在while循环顶部打印字符串发现的- 它在提取第一个单词后从未改变过.
然后,当你执行下一步时find,它会找到完全相同的空间,而不是先跳过空格然后find正确调用.您需要在每个之后跳过空格find,确保不要超出字符串的末尾.
这是我的解决方案.根据需要使用它.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> split( const string &str, const char &delim ) {
typedef string::const_iterator iter;
iter beg = str.begin();
vector<string> tokens;
while(beg != str.end()) {
//cout << ":" << beg._Myptr << ":" << endl;
iter temp = find(beg, str.end(), delim);
if(beg != str.end())
tokens.push_back(string(beg, temp));
beg = temp;
while ((beg != str.end()) && (*beg == delim))
beg++;
}
return tokens;
}
int main () {
vector<string> x = split ("Hello, my name is Bob. ", ' ');
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果没有while循环结束时的空格跳过代码,则输出为:
:Hello, my name is Bob. :
: my name is Bob. :
: my name is Bob. :
: my name is Bob. :
: my name is Bob. :
: my name is Bob. :
: my name is Bob. :
: my name is Bob. :
Run Code Online (Sandbox Code Playgroud)
等等,无限的.使用跳过代码,您将获得:
:Hello, my name is Bob. :
:my name is Bob. :
:name is Bob. :
:is Bob. :
:Bob. :
Run Code Online (Sandbox Code Playgroud)
我必须喜欢Boost,因为它也为此提供了一个方便的解决方案:
std::vector<std::string> Split(const std::string &s, const std::string &d)
{
std::vector<std::string> v;
for (boost::split_iterator<std::string::iterator> i = boost::make_split_iterator(s, boost::first_finder(d, boost::is_iequal()));
i != boost::split_iterator<std::string::iterator>();
++i) {
v.push_back(boost::copy_range<std::string>(*i));
}
return v;
}
Run Code Online (Sandbox Code Playgroud)
这是另一个很好的简短的基于Boost的版本,它使用整个字符串作为分隔符:
std::vector<std::string> result;
boost::iter_split(result, str, boost::first_finder(delim));
Run Code Online (Sandbox Code Playgroud)
或不区分大小写:
std::vector<std::string> result;
boost::iter_split(result, str,
boost::first_finder(delim, boost::is_iequal()));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7219 次 |
| 最近记录: |