簡體   English   中英

c - 在計算c中字符串的長度時如何不計算空格

[英]how not to count spaces while counting the length of string in c

我正在使用以下代碼計算字符串中的空格,但我不想計算空格。

#include<stdio.h>
#include<conio.h>

void main()
{
   char*ptr,str[30];
   int size=0;
   int word=0;

   puts("enter the string");
   gets(str);
   fflush(stdin);

   for(ptr=str;*ptr!='\0',ptr++)
   {
       size++;
   }

   printf("size of string is = %d",size);
   getchar();
}

TL; 博士; 答案:當值(在那個指針位置)是一個空格時,跳過計數器( size )增量。

請自己編寫代碼並將結果更新給我們。

也就是說,恕我直言,首先你應該注意(並糾正)一些事情,因為

  1. void main()不是標准的。 改用int main(void)
  2. 永遠不要使用gets()它會受到緩沖區溢出問題的嚴重影響。 請改用fgets()
  3. fflush(stdin)未定義的行為 盡快擺脫它。

嘗試使用指針算術代替以下代碼:

while (*ptr) {
    if (*ptr != ' ') {
        size++;
    }
}

這將循環遍歷字符,直到遇到空終止符 '\\0',並根據需要遞增。

嘗試這個

int my_strlen(char *str)
{
int i, j = 0;
while (str[i] != '\0')
{
   if (str[i] != ' ')
       ++j;
   ++i;
}
return j;
}

在你的循環中:

跳過空格

計算所有其他字符

暫無
暫無

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

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