Как считать слова из массива символов в C ++ - PullRequest
0 голосов
/ 06 апреля 2019

У меня проблема с попыткой получить буквы из массива символов в мою функцию wordCount для подсчета количества слов в каждом элементе массива.Я считаю, что мне следует манипулировать только этой функцией, но неясно, как получить отдельные буквы из массива testCases в функцию подсчета слов.

После этого я предположил бы, что буду использовать операторы if, чтобы проверить, являются ли символы, считанные в wordCount, либо буквами, а когда они заканчиваются, считать их как слово.

код ниже:

#include <iostream>
using namespace std;

// Function Prototype
int wordCount (char *userEntry);

int main() {
// Constants
const int MAX_LENGTH = 150;

// Local variables
char testCases[][MAX_LENGTH + 1] = { "0",
    "    1   22    3333    44444 ",
    "     testing    ",
    "a",
    "onetwothree",
    "one two three",
    "    testing    a    11   222  three  4  five  ",
    "a b c d e f" };
int wCount = 0;

// loop through test cases and display number of words in each
for (char *entry : testCases) {
    wCount = wordCount(entry);
    cout << "\nNumber of words in the test case '" << entry << "' is: " 
<< wCount << endl;
}

return EXIT_SUCCESS;
}

/*
Function Name:  wordCount
This function counts the # of space-delimited words
in a character string, and returns the count to the
caller.
NOTE: A word is defined as one or more alphabetic
characters separated by one or more spaces,
unless it is the only alphabetic character(s).
*/

int wordCount (char *userEntry) {

return 0;
}

1 Ответ

2 голосов
/ 06 апреля 2019

Строки в c ++ заканчиваются нулем, что означает, что после их последнего символа есть символ '\0' с символьным кодом 0x00. Чтобы прочитать каждый символ массива строк / символов, вы просто используете оператор индекса []. Строки в C ++, как и другие массивы, индексируются от 0 до n-1

вот пример для цикла, который будет читать символ строки в символьную переменную.

void iterate_through_characters(const char* aString) {
    // starting at n=0 check each n and make sure it is shorter than the
    // width of the array
    // and that it's not the null terminating character
    for (int n = 0; (n < MAX_LENGTH + 1) && (aString[n] != '\0'); n++) {
        // take the character out of the index in the string and store it in aCharacter
        char aCharacter = aString[n];
    }
}

Для вашего особого случая вы также хотели бы отслеживать, находитесь ли вы в слове или нет, и считать только новое слово, если вы еще не в слове. Следующая функция реализует это.

int wordCount(const char* input) {

    // this is true if we're in a word
    bool inWord = false; 

    // the number of words we've seen defaulting to 0, no words
    int result = 0;

    for (int n = 0; (n < MAX_LENGTH + 1) && (aString[n] != '\0'); n++) {
       // if this is a space we're not in a word
       if (aString[n] == ' ') {
           inWord = false; // if we were in a word, we aren't now
       } else if (!inWord) {
           inWord = true; // if we weren't in a word, we are now
           result ++; // increment the number of words we've seen 
       }
   }
   return result;
}
...