簡體   English   中英

為什么這仍在計算字符串中的空格?

[英]Why is this still counting spaces within a String?

我剛剛開始編寫代碼,我需要幫助弄清楚為什么這個循環會計算字符串中的空格。

據我了解,這段代碼應該告訴計算機不計算空格“/ 0”,如果循環遍歷字符串並且它是任何其他字符,則增加計數。

int main(void)
{

    string t = get_string("Copy & Past Text\n");
    int lettercount = 0;

   for (int i = 0; t[i] != '\0'; i++)
    {
          lettercount++;
        
    }

    printf("%i", lettercount);

    printf("/n");
}

\0代表 null 字符,而不是空格。 它位於字符串的末尾以指示它們的結尾。 要僅檢查空格,請在循環內添加條件語句。

int main(void)
{
    string t = get_string("Copy & Past Text\n");
    int lettercount = 0;

    for (int i = 0; t[i] != '\0'; i++)
    {
        if (t[i] != ' ')
            lettercount++;
    }

    printf("%i", lettercount);

    printf("\n");
}

空格被認為是一個字符,您的代碼遍歷字符串(字符數組)並計算字符,直到它到達字符串終止字符'\0'。

編輯:在循環 if(t[i].= ' ') 中設置一個 if 條件,您將不再計算空格。

您誤解了 C 字符串的性質。

字符串是具有低值 ('\0') 的字符數組,用於標記字符串的結尾。 在字符串中,一些字符可能是空格(' ' 或 x20)。

所以“ t[i].= '\0' ”條件標志着循環的結束。

一個簡單的改變:

if ( t[i] != ' ') {
    lettercount++;
}

將使您的程序正常工作。

這個for循環

for (int i = 0; t[i] != '\0'; i++)

迭代直到當前字符是終止零字符'\0' ,它是一個 null 字符。 所以字符不計算在內。

在 C 中有標准 function isalpha在 header <ctype.h>中聲明,用於確定字符是否代表字母。

請注意,用戶可以例如在字符串中輸入標點符號。 或者他可以使用制表符'\t'而不是空格符' ' 例如,他的輸入可能看起來像"~!@#$%^&" ,其中沒有任何字母。

所以用以下方式編寫循環會更正確

size_t lettercount = 0;

for ( string s = t; *s; ++s )
{
    if ( isalpha( ( unsigned char )*s ) ) ++lettercount;
}

printf("%zu\n", lettercount );

這個說法

printf("/n");

應被刪除。 我想你的意思是

printf("\n");

那就是你要 output 換行符'\n'。 但是這個字符可以插入到前面的printf調用中,如上所示

printf("%zu\n", lettercount );

空終止符是由字符串文字組成的字符數組中的最后一個前導元素(例如Hello there!\0 )。 它終止一個循環並防止進一步繼續讀取下一個元素。

請記住,空終止符不是空格字符。 兩者都可以用以下方式表示:

\0 - null terminator | ' ' - a space

如果要計算除空格以外的字母,請嘗試以下操作:

#include <stdio.h>

#define MAX_LENGTH 100

int main(void) {
    char string[MAX_LENGTH];
    int letters = 0;

    printf("Enter a string: ");
    fgets(string, MAX_LENGTH, stdin);

    // string[i] in the For loop is equivalent to string[i] != '\0'
    // or, go until a null-terminator occurs
    for (int i = 0; string[i]; i++)
        // if the current iterated char is not a space, then count it
        if (string[i] != ' ')
            letters++;

    // the fgets() reads a newline too (enter key)
    letters -= 1;

    printf("Total letters without space: %d\n", letters);

    return 0;
}

你會得到類似的東西:

Enter a string: Hello world, how are you today?
Total letters without space: 26

如果字符串文字沒有任何空終止符,那么除非程序員手動給出要讀取的最大元素數,否則無法阻止它被讀取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM