首页 > 解决方案 > 将句子拆分为单词时缺少字符串的最后一个单词

问题描述

我错过了字符串的最后一个单词。这是我用来将单词存储到数组中的代码。

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;
}

标签: c++

解决方案


@Casey的非常好的方法之后,但添加了使用std::vector而不是数组,允许您将一行分成尽可能多的单词。使用std::stringstreamand 提取 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_ofandstd::string::find_first_not_of和一组分隔符来通过字符串查找标记中的第一个字符,std::string::find_first_of然后使用 跳过分隔符到下一个标记的开头std::string::find_first_not_of。这涉及更多的算术,但是一种更灵活的选择。


推荐阅读