c++ - 将句子拆分为单词时缺少字符串的最后一个单词
问题描述
我错过了字符串的最后一个单词。这是我用来将单词存储到数组中的代码。
string arr[10];
int Add_Count = 0;
string sentence = "I am unable to store last word"
string Words = "";
for (int i = 0; i < sentence.length(); i++)
{
if (Sentence[i] == ' ')
{
arr[Add_Count] = Words;
Words = "";
Add_Count++;
}
else if (isalpha(Sentence[i]))
{
Words = Words + sentence[i];
}
}
让我们打印 arr:
for(int i =0; i<10; i++)
{
cout << arr[i] << endl;
}
解决方案
继@Casey的非常好的方法之后,但添加了使用std::vector
而不是数组,允许您将一行分成尽可能多的单词。使用std::stringstream
and 提取 with>>
允许一种简单的方法来标记句子,同时忽略前导、多个包含和尾随空格。
例如,您可以这样做:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main (void) {
std::string sentence = " I am unable to store last word ",
word {};
std::stringstream ss (sentence); /* create stringstream from sentence */
std::vector<std::string> words {}; /* vector of strings to hold words */
while (ss >> word) /* read word */
words.push_back(word); /* add word to vector */
/* output original sentence */
std::cout << "sentence: \"" << sentence << "\"\n\n";
for (const auto& w : words) /* output all words in vector */
std::cout << w << '\n';
}
示例使用/输出
$ ./bin/tokenize_sentence_ss
sentence: " I am unable to store last word "
I
am
unable
to
store
last
word
如果您需要更细粒度的控制,您可以使用std::string::find_first_of
andstd::string::find_first_not_of
和一组分隔符来通过字符串查找标记中的第一个字符,std::string::find_first_of
然后使用 跳过分隔符到下一个标记的开头std::string::find_first_not_of
。这涉及更多的算术,但是一种更灵活的选择。
推荐阅读
- objective-c - NSArray 分配导致“多个未排序的修改”
- xml - 没有重复的可选元素的 DTD
- scala - 无法让 println 在分组整数范围映射函数中工作
- java - java中的https POST调用
- java - 有没有办法从 InputStream 获取文件
- cassandra-3.0 - java驱动程序显示一致性级别为空
- kerberos - 是否可以使用wiremock将http流量记录/回放到kerberized端点,例如纱线休息API?
- android - 我正在使用 Ionic 和 React 并尝试实现深度链接,我正在使用 App.getLaunchUrl(); 从电容器它返回空?
- google-apps-script - 谷歌电子表格将自定义菜单添加到列表表
- reactjs - 在 react-router 中使用 Redirect 后,ComponentDidMount 没有触发