簡體   English   中英

計算不帶空格的字符串中的字母

[英]Count Letters in String without Spacebar

我想用函數strlen()計算字符串的長度(包括空格),而沒有空格的字符串的長度。 前者有效,但后者有問題。

例:

Hello User//including spaces:10 letters//without spaces:9

當我輸入不帶空格的單詞時,程序總是計數:100,而帶1個空格:我得到99,依此類推。

#include<stdio.h>
#include<stdlib.h>

#define N 100

int main()
{
    int counter1 = 0, i;
    char string1[N] = {0};
    {
        gets(string1);
        printf("\nYour Text:\n%s",string1);
        printf("\nLength of String:%i Letters(with spaces)", strlen(string1));
        for(i=0; i<N; i++)
        {
            if(string1[i] != ' ' && string1[i] != '0')
                counter1++;
        }
        printf("Number of Letters(without spaces): %i",counter1);
    }
    return 0;
}

您尚未考慮字符串以'\\ n'結尾。 您的代碼將在0到100之間運行,因此您總是得到100。 您可以使用以下方式更改代碼:

i=0;
while(string1[i]!='\n' && string1[i]!='\0')
{
  if(string1[i]!=' ') {
      counter1++;
  }

  i++;
}

請注意,在C中,默認的字符串定界符為'\\ 0'而不是0

如果您想要C ++答案(確實添加了C ++標簽),則可以執行以下操作:

std::string tmp(str);
int cpt = std::count_if(tmp.begin(),tmp.end(),[](char c){return c != ' ';});

在C#中:

int numberOfChars = yourString != null ? yourString.Replace(" ", "").Count() : 0;

祝你今天愉快,

阿爾貝托

while(str[i]!='\0')
 {
     if(str[i]!=' ')
     {
         count++;
     }
     i++;
 }

此循環有效或更改您的for循環

for(i=0; i<strlen(string1); i++)
        {
            if(string1[i] != ' ' && string1[i] != '0')
                counter1++;
        }

自從你用過

for(i=0; i<N; i++)

其中N=100並且c不會檢查越界訪問,因此循環繼續直到i=100這導致count=100-number of spaces

您必須檢查NULL(string1 [i] == 0)字符。 一旦遇到NULL,請從for循環中斷開。

我的方法是:

int len = strlen(string1);
int lenWithoutSpace = len;
for(int i=0; i<len; ++len){
  if(string1[i]==' '){
    lenWithoutSpace--;
  }
}

試試下面的代碼:

int main()
{
int counter1=0,i;
char string1[N]={0};
{   
gets(string1);
printf("\nYour Text:\n%s",string1);
printf("\nLength of String:%i Letters(with spacebar)",strlen(string1));
 for(i=0;i<strlen(string1);i++)
{
  if(string1[i]!=' '&&string1[i]!='0')
    counter1++;
}    
printf("Number of Letters(without spacebar): %i",counter1);
}
return 0;
}

您的循環總計100,不包括空格和“ 0”,我相信您希望它為“ \\ 0”。 將循環更改為0到strlen(string1)和if條件,它應該可以正常工作。 雖然可以有更好的方法。

暫無
暫無

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

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