C语言 C中的字符计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3745653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:28:02  来源:igfitidea点击:

Counting characters in C

ccountcharacter

提问by James

I'm trying to write a program that counts all the characters in a string. I originally had it, but then realized I can't count spaces. I can't see why this does not work.

我正在尝试编写一个程序来计算字符串中的所有字符。我最初拥有它,但后来意识到我无法计算空格。我不明白为什么这不起作用。

for(m=0; z[m] != 0; m++) {
    if(z[m] != ' ') {
        charcount ++;
    }
}

Any assistance appreciated.

任何帮助表示赞赏。

Edit* Does it make a difference if the input(strings) are being scanned in like this? And yes, everything is initialized. I've tried printing what z[m] evaluates too and it isn't the actual value of the string at "m", I think this is the problem.

编辑* 如果输入(字符串)像这样被扫描,会有什么不同吗?是的,一切都已初始化。我也尝试打印 z[m] 评估的内容,但它不是“m”处字符串的实际值,我认为这就是问题所在。

for(j=0; j<7; j++){
    printf("Enter a string:\n");
    scanf("%s", z);
        for(m=0; z[m] != 0; m++){
                if(z[m] != ' '){
                charcount ++;
                }
        }

回答by T.J. Crowder

You need to initialize charcount. Other than that, it should work, provided that zis a zero-terminated array of characters and mis an intor similar. I would probably write just z[m]rather than z[m] != 0(since !0 = true and 0 = false), but both work. There are more efficient ways of doing it (although these days I bet a compiler will handle converting this into a pointer-based loop for you).

您需要初始化charcount. 除此之外,它应该可以工作,前提是它z是一个以零结尾的字符数组并且m是一个int或类似的。我可能会写z[m]而不是z[m] != 0(因为 !0 = true 和 0 = false),但两者都有效。有更有效的方法来做到这一点(尽管现在我打赌编译器会为您处理将其转换为基于指针的循环)。

Here's a complete, correct example with minimal edits:

这是一个完整、正确的示例,并进行了最少的编辑:

const char * z = "testing one two three";
int m;
int charcount;

charcount = 0;
for(m=0; z[m]; m++) {
    if(z[m] != ' ') {
        charcount ++;
    }
}

If you're using a Stringclass of some kind rather than an old-fashioned C null-terminated array, you'll want to look at that class for how to loop through it.

如果您使用的String是某种类而不是老式的 C 以空字符结尾的数组,您将需要查看该类以了解如何遍历它。

All of the above also assumes you're dealing with ASCII strings. If you're dealing with UTF-encoded strings, you have to handle multi-byte characters.

以上所有内容还假设您正在处理 ASCII 字符串。如果您正在处理 UTF 编码的字符串,则必须处理多字节字符。



Re your edit: It makes a big difference: scanfwill stop on the first blank(I'd forgotten that). It might make an even bigger difference than that, though, if you're not declaring zcorrectly. (I'd also recommend using a field width when using scanffor reading strings [or avoiding scanfentirely]; otherwise, you have no control over the number of chars it will try to store, and so in theory, no buffer will ever be big enough to avoid an overflow. More here: http://www.crasseux.com/books/ctutorial/String-overflows-with-scanf.html)

重新编辑:它有很大的不同:scanf在第一个空白处停止(我忘记了)。但是,如果您没有z正确声明,它可能会产生更大的差异。(我还建议在scanf用于读取字符串 [或scanf完全避免]时使用字段宽度;否则,您无法控制它将尝试存储的字符数,因此理论上,任何缓冲区都不会足够大以避免溢出。更多信息:http: //www.crasseux.com/books/ctutorial/String-overflows-with-scanf.html

回答by Anonymous

You can use strlen()

您可以使用 strlen()

I'd suggest using a whileloop, and to use more meaningful variable names

我建议使用while循环,并使用更有意义的变量名

m = textIndex 
z = text

Something like this would work

像这样的东西会起作用

while (text[textIndex] != 0x00)
{
  textIndex++;
}

回答by Martin T?rnwall

Instead of using scanf, try fgets like so:

不要使用 scanf,而是像这样尝试 fgets:

char input[256];
fgets(input, sizeof(input), stdin);

fgets will read an entireline from a file. As such, passing stdin as the file handle will make it read from standard input, which in most cases will be bound to the console. One thing to watch out for, though, is that the string you get from fgets might include the newline character. Rather than explicitly checking your strings for inequality with the space character (' '), I suggest using the isspace function from ctype.h, which will check for various forms of whitespace (including a regular space and newline).

fgets 将从文件中读取行。因此,将 stdin 作为文件句柄传递将使其从标准输入读取,在大多数情况下将绑定到控制台。不过,需要注意的一件事是,您从 fgets 获得的字符串可能包含换行符。我建议使用 ctype.h 中的 isspace 函数,而不是用空格字符 (' ') 显式检查字符串的不等式,该函数将检查各种形式的空格(包括常规空格和换行符)。

Here is a complete, runnable example:

这是一个完整的、可运行的示例:

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

int count_nonspace(const char* str)
{
 int count = 0;
 while(*str)
 {
  if(!isspace(*str++))
   count++;
 }
 return count;
}

int main()
{
 char input[256];
 fgets(input, sizeof(input), stdin);
 printf("%d\n", count_nonspace(input));
}

回答by user411313

Yes, there is a difference on input-scan with scanf:

是的,使用 scanf 进行输入扫描是有区别的:

    scanf("%s", z);
...
                if(z[m] != ' '){

scanf("%s"...) always breaks at space-character, therefore your if ever is true. Better you use fgets to read from stdin,

scanf("%s"...) 总是在空格字符处中断,因此您的if ever 为 true。最好使用 fgets 从标准输入读取,

#define MAXINPUT 80
char line[MAXINPUT];
for(j=0; j<7; j++) {
  printf("Enter a string:\n");
  if( fgets( line, 80, stdin ) )
  {
    char *c=line;
    if( strchr(line,'\n') ) *strchr(line,'\n')=0;
    while( *c )
    {
      if( *c!=' ' )
        ++charcount;
      ++c;
    }
  }
}

Or if you want WHITE-spaces then take

或者如果你想要WHITE-spaces 然后拿

#include <ctype.h>
...
if( !isspace(*c) )