簡體   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