C++ 基于C++;
可能重复:C++ 基于C++;,c++,arrays,sentence,C++,Arrays,Sentence,可能重复: 如何将一组由空格分隔的单词读入数组 假设我有这样一句话: “我喜欢青蛙” 这个阵列: string mySentenceArray[2] 我想做点什么 mySentenceArray[0] = I mySentenceArray[1] = like mySentenceArray[2] = frogs 举个例子。(请不要告诉我硬编码我刚才写的句子,这是一个例子。)你可以将一个字符串转换成一系列的标记,然后将这些标记放入一个数组中。考虑这一点:有几种方式: 使用。但它是C函数,而
如何将一组由空格分隔的单词读入数组 假设我有这样一句话: “我喜欢青蛙” 这个阵列:
string mySentenceArray[2]
我想做点什么
mySentenceArray[0] = I
mySentenceArray[1] = like
mySentenceArray[2] = frogs
举个例子。(请不要告诉我硬编码我刚才写的句子,这是一个例子。)你可以将一个字符串转换成一系列的标记,然后将这些标记放入一个数组中。考虑这一点:
有几种方式:
除非我有其他用途来证明添加额外库的合理性,否则我可能只会使用
stringstream
:
std::istringstream buffer("I like frogs");
std::vector<std::string> words((std::istream_iterator<std::string>(buffer)),
std::istream_iterator<std::string>());
std::copy(words.begin(), words.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
std::istringstream缓冲(“我喜欢青蛙”);
std::向量字((std::istream_迭代器(缓冲区)),
std::istreamu迭代器();
复制(words.begin(),words.end(),
std::ostream_迭代器(std::cout,“\n”);
仅使用标准库:
istringstream sentence("I like frogs");
vector<string> words(
(istream_iterator<string>(sentence)),
(istream_iterator<string>()));
这个怎么样?只需使用boost,或者编写自己的函数。这甚至不难。不要在链接中使用解决方案。它的设计很差,也没有它所说的优雅。
strtok
在std::string
上使用很不方便,因为它需要一个可变字符数组,并且无法直接从字符串访问它。它也不是线程安全的。
string sentence("I like frogs");
vector<string> words;
boost::algorithm::split(words, sentence, boost::algorithm::is_space());