繁体   English   中英

如何将用户输入的字符串加入三个数组并打印结果?

[英]How do I join a user-entered string to three arrays and print the result?

我有一个程序,我写了一个文本,它计算其中的字母数、单词数和句子数,但我想问用户一个问题,然后分配结果或将其组合成三个数组然后输出一次结果,而不是每次都要求用户分别计算字母,单词,以及锐度上的句子

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) {
    //  character count
    string text = get_string("text: ");
    int number1 = 0;
    for (int i = 0; i < strlen(text); i++) {
        if (text[i] != ' ' && isalpha(text[i])) {
            number1++;
        }
    }

    //   Word counting calculator
    string words = get_string("text: ");
    int number2 = 0;
    for (int i = 0; i < strlen(words); i++) {
        if (words[i] == ' ') {
            number2++;
        }
    }

    //    Calculate the number of sentences
    string sentences = get_string("text: ");
    int number3 = 0;
    for (int i = 0; i < strlen(sentences); i++) {
        if (sentences[i] == '?' || sentences[i] == '!' || sentences[i] == '.') {
            number3++;
        }
    }
    printf("%i %i %i\n", number1, number2, number3);
}

但是我想问用户一个问题然后将结果分发或将其组合成三个数组然后输出一次结果而不是每次都要求用户分别计算字母,单词和句子

在这种情况下,不要再次要求输入:

...
    //  character count
    string text = get_string("text: ");
    int number1 = 0;
    for (int i = 0; i < strlen(text); i++) {
        if (text[i] != ' ' && isalpha(text[i])) {
            number1++;
        }
    }

    //   Word counting calculator
    int number2 = 0;
    for (int i = 0; i < strlen(text); i++) {
        if (text[i] == ' ') {
            number2++;
        }
    }

    //    Calculate the number of sentences
    int number3 = 0;
    for (int i = 0; i < strlen(text); i++) {
        if (text[i] == '?' || text[i] == '!' || text[i] == '.') {
            number3++;
        }
    }

然后你甚至可以将所有循环组合成一个循环:

    int number1 = 0;
    int number2 = 0;
    int number3 = 0;

    string text = get_string("text: ");
    for (int i = 0; i < strlen(text); i++) {

        //  character count
        if (text[i] != ' ' && isalpha(text[i])) {
            number1++;
        }

        //   Word counting calculator
        if (text[i] == ' ') {
            number2++;
        }

        //    Calculate the number of sentences
        if (text[i] == '?' || text[i] == '!' || text[i] == '.') {
            number3++;
        }
    }

我不明白计数字母和组合字符串之间的关系。 但无论如何,您可以使用 <string.h> 中的内置函数,例如,您可以使用以下方法组合两个字符串: strcat(); .

暂无
暂无

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

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