如何在c ++这样的段落中找到单词的序列号(索引)?

时间:2016-04-25 21:16:50

标签: c++ indexing word

我正在开发一个项目,需要找到段落中每个单词的单词数量和索引...我已经写了一个代码来计算一个字符串中的单词数但是我坚持找单词的索引,

如:嗨约翰你好我想你...

我需要打印索引,如:0 1 2 3 4 5 6 7

这是代码:

int _tmain(int argc, _TCHAR* argv[])
{

    int count_words(std::string);


    std::string input_text;
    std::cout<< "Enter a text: ";
    std::getline(std::cin,input_text);

    int number_of_words=1;
    int counter []={0};
    for(int i = 0; i < input_text.length();i++)
        if(input_text[i] == ' ')

            number_of_words++;

   std::cout << "Number of words: " << number_of_words << std::endl;
    //std:: cout << number_of_words << std::endl;
    system ("PAUSE");   

}

2 个答案:

答案 0 :(得分:0)

希望这会有所帮助。编辑包括使用count_words函数。

public static int[] blackjackByIteration(int[] hands) {
    OptionalInt oi = Arrays.stream(hands).filter(i -> i <= 21).max();
    if (oi.isPresent()) {
        int value = oi.getAsInt();
        return IntStream.range(0, hands.length).filter(i -> hands[i] == value).toArray();
    }
    return new int[0];
}

答案 1 :(得分:0)

我不确定我是否理解这个问题。你只需要打印“索引”??像这样? (使用您自己的代码)

#include <iostream>
#include <vector>
#include <string>

void stringTokenizer(const std::string& str, const std::string& delimiter, std::vector<std::string>& tokens) {
   size_t prev = 0, next = 0, len;

   while ((next = str.find(delimiter, prev)) != std::string::npos) {
     len = next - prev;
     if (len > 0) {
       tokens.push_back(str.substr(prev, len));
     }
      prev = next + delimiter.size();
   }

  if (prev < str.size()) {
   tokens.push_back(str.substr(prev));
  }
}

int main()
{

  std::vector <std::string> split;
  std::string input_text;
  std::cout<< "Enter a text: ";
  std::getline(std::cin,input_text);

  stringTokenizer(input_text, " ", split);
  int number_of_words = 0;
  for (std::vector<std::string>::iterator it = split.begin(); it != split.end(); it++, number_of_words++) {
    std::cout << *it << " " << number_of_words << std::endl;
  }

}