简体   繁体   English

如何用句子填充数组?

[英]How to fill an array with a sentence?

For instance i have the sentence " I am Piet".例如,我有一句话“我是皮特”。 I want to fill this sentence into an array in a way that I[0], am[1] Piet[2].我想以 I[0], am[1] Piet[2] 的方式将这句话填充到数组中。 Below is the code i've made.下面是我制作的代码。 The problem is that the sentence is filled in each element of the array.问题是在数组的每个元素中都填充了句子。

#include <iostream>
#include <string>
using namespace std;

// function to populate my array
void populateMyArray(string*myArray, string sentence, int size)
{
for (int i = 0; i < size; i++)
{
*myArray = sentence;
    myArray++;
}
}

// function to count works in the sentence
int countWords(string x)
{
int Num = 0;
char prev = ' ';

for (unsigned int i = 0; i < x.size(); i++) {

    if (x[i] != ' ' && prev == ' ') Num++;

    prev = x[i];
}
return Num;
}

int main()
{
string sentence1;

cout << "Please enter a line of text:\n";
getline(cin, sentence1);

int nWords1 = countWords(sentence1);

string *arr1 = new string[nWords1];

populateMyArray(arr1, sentence1, nWords1); //populate array1

for (int i = 0; i < nWords1; i++)
{
    cout << "sentence one: " << arr1[i] << "\n";
}

system("PAUSE");
}

You can use vector in order to save data and each time you should use space between two words and you will store each string type into vector array您可以使用 vector 来保存数据,并且每次应该在两个单词之间使用空格时,您会将每个字符串类型存储到 vector 数组中

 #include<bits/stdc++.h>
    using namespace std;
        main()
        {
            string s;
            getline(cin,s);
            vector<string> ss;
            string temp = "";
            s +=" ";
            for(int i = 0 ; i < s.size();i ++){
                if(s[i] != ' ')
                    temp += s[i];
                else{
                        ss.push_back(temp);
                        temp = "";
                }
            }
            for(int i = 0 ; i < ss.size();i ++)
                cout << ss[i] <<" ";
        }

Instead of using an array, use a std::vector instead.不要使用数组,而是使用std::vector This way you don't have to worry about variable word sizes or overflowing anything in case a word or sentence is too long.这样您就不必担心可变的单词大小或在单词或句子太长的情况下溢出任何内容。 Rather you can just do something like this:相反,您可以执行以下操作:

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

int main() {
  // Get all words on one line
  std::cout << "Enter words: " << std::flush;
  std::string sentence;
  getline(std::cin, sentence);

  // Parse words into a vector
  std::vector<std::string> words;
  std::string word;
  std::istringstream iss(sentence);
  while( iss >> word ) {
    words.push_back(word);
  }

  // Test it out.
  for(auto const& w : words) {
    std::cout << w << std::endl;
  }
}

For an example sentence of I like cats and dogs equally you will have: words[0] = I , words[1] = like and so on.对于I like cats and dogs equally例句,您将有: words[0] = Iwords[1] = like等等。

How to think like a programmer.如何像程序员一样思考。

The first thing we need is definitions of the beginning or a word and the end of a word.我们需要的第一件事是对词首或词和词尾的定义。 You might think that the beginning of a word is a non-space preceded by a space and the end of a word is a non-space followed by a space.您可能认为单词的开头是前面有空格的非空格,单词的结尾是非空格后跟空格。 But those definitions are wrong because they ignore the possibility of words at the start or end of the string.但是这些定义是错误的,因为它们忽略了字符串开头或结尾的单词的可能性。 The correct definition of the beginning of a word is a non-space at the start of the string or a non-space preceded by a space.单词开头的正确定义是字符串开头的非空格或前面有空格的非空格。 Similarly the end of a word is a non-space at the end of the string or a non-space followed by a space.类似地,单词的结尾是字符串末尾的非空格或后跟空格的非空格。

Now we have the definitions we capture them in two functions.现在我们有了在两个函数中捕获它们的定义。 It's very important to break complex problems down into smallier pieces and the way to do that is by writing functions (or classes).将复杂的问题分解成更小的部分非常重要,而这样做的方法是编写函数(或类)。

bool beginning_of_word(string str, int index)
{
    return str[index] != ' ' && (index == 0 || str[index - 1] == ' ');
}

bool end_of_word(string str, int index)
{
    return str[index] != ' ' && (index == str.size() - 1 || str[index + 1] == ' ');
}

Now we're getting closer, but we still need the idea of finding the next start of word, or the next end of word, so we can loop through the sentence finding each word one at a time.现在我们越来越近了,但我们仍然需要找到单词的下一个开头或单词的下一个结尾的想法,因此我们可以循环遍历句子,一次找到一个单词。 Here are two functions for finding the next start and next end of word.这里有两个函数用于查找单词的下一个开头和下一个结尾。 They start from a given index and find the next index that is the start or end of a word.它们从给定的索引开始,并找到作为单词开头或结尾的下一个索引。 If no such index is found they return -1.如果没有找到这样的索引,它们返回 -1。

int next_beginning_of_word(string str, int index)
{
    ++index;
    while (index < str.size())
    {
        if (beginning_of_word(str, index))
            return index; // index is a start of word so return it
        ++index;
    }
    return -1; // no next word found
}

int next_end_of_word(string str, int index)
{
    ++index;
    while (index < str.size())
    {
        if (end_of_word(str, index))
            return index; // index is an end of word so return it
        ++index;
    }
    return -1; // no next word found
}

Now we have a way of looping through the words in a sentence we're ready to write the main loop.现在我们有了一种循环遍历句子中单词的方法,我们准备编写主循环。 We use substr to break the words out of the sentence, substr takes two parameters the index of the start of the word and the length of the word.我们使用substr将单词从句子中拆分出来, substr两个参数,单词开头的索引和单词的长度。 We can get the length of the word by substracting the start from the end and adding one.我们可以通过从末尾减去开头并加一来获得单词的长度。

int populateMyArray(string* array, string sentence)
{
    // find the first word
    int start = next_beginning_of_word(sentence, -1);
    int end = next_end_of_word(sentence, -1);
    int count = 0;
    while (start >= 0) // did we find it?
    {
        // add to array
        array[count] = sentence.substr(start, end - start + 1);
        ++count;
        // find the next word
        start = next_beginning_of_word(sentence, start);
        end = next_end_of_word(sentence, end);
    }
    return count;
}

Now for extra credit we can rewrite countWords using next_beginning_of_word现在对于加分,我们可以重写countWords使用next_beginning_of_word

int countWords(string sentence)
{
    int start = next_beginning_of_word(sentence, -1);
    int count = 0;
    while (start >= 0)
    {
        ++count;
        start = next_beginning_of_word(sentence, start);
    }
    return count;
}

Notice the similarity of the countWords and the populateMyArray functions, the loops are very similar.注意countWordspopulateMyArray函数的相似性,循环非常相似。 That should give you confidence.那应该会给你信心。

This is the way programmers work, when you have a problem that is too complex for you to handle, break it down into smaller pieces.这就是程序员的工作方式,当你遇到一个太复杂而无法处理的问题时,把它分解成更小的部分。

If I understood correctly you are trying to split the input sentence into words.如果我理解正确,您正在尝试将输入句子拆分为单词。

You could do it like this:你可以这样做:

void populateMyArray(string *myArray, string sentence, int size)
{
  int firstCharIndex = -1;
  char prev = ' ';

  for (unsigned int i = 0; i < sentence.size(); i++) {
    // Find the first character index of current word
    if (sentence[i] != ' ' && prev == ' ') {
      firstCharIndex = i;
    }
    // Check if it's the end of current word
    // and get substring from first to last index of current word
    else if (sentence[i] == ' ' && prev != ' ') {
      *myArray = sentence.substr(firstCharIndex, i - firstCharIndex);
      myArray++;
    }
    prev = sentence[i];
  }

  // For the last word
  if (firstCharIndex != -1 && sentence[sentence.size() - 1] != ' ') {
    *myArray = sentence.substr(firstCharIndex, sentence.size() - firstCharIndex);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM