C++ 函数将字符串拆分成单词 [英] C++ function split string into words
本文介绍了C++ 函数将字符串拆分成单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用 C++ 编写一个函数,将我的字符串测试拆分为数组中的单独单词.我似乎无法循环正确的东西...有人有任何想法吗?它应该打印这个"
im trying to write a function in c++ that splits my string test into separate words in an array. i cant seem to the stuff in loop right... anyone got any ideas? it should print "this"
void app::split() {
string test = "this is my testing string.";
char* tempLine = new char[test.size() + 1];
strcpy(tempLine, test.c_str());
char* singleWord;
for (int i = 0; i < sizeof(tempLine); i++) {
if (tempLine[i] == ' ') {
words[wordCount] = singleWord;
delete[]singleWord;
}
else {
singleWord[i] = tempLine[i];
wordCount++;
}
}
cout << words[0];
delete[]tempLine;
}
推荐答案
如果你只想显示字符串中的单词,请使用:
If you just want to display words from string use:
#include <algorithm>
#include <iterator>
#include <sstream>
//..
string test= "this is my testing string.";
istringstream iss(test);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
ostream_iterator<string>(cout, "\n"));
else 处理这些词使用 std::string
else to process those words uses std::vector
of std::string
std::vector<std::string> vec;
istringstream iss(test);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(vec));
这篇关于C++ 函数将字符串拆分成单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文