计算C中的字符 [英] Counting characters in C

查看:137
本文介绍了计算C中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个计算字符串中所有字符的程序。我原来有它,但后来意识到,我不能算空间。

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 ++;
    }
}

编辑*如果输入(字符串)以这样的方式扫描,它会有所不同吗?是的,一切都被初始化。我试着打印z [m]评估,它不是字符串在m的实际价值,我认为这是问题。

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.

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 ++;
                }
        }


推荐答案

需要初始化 charcount 。除此之外,它应该工作,只要 z 是一个零终止的字符数组, m code> int 或类似的。我可能只写 z [m] ,而不是 z [m]!= 0 和0 = false),但两者都工作。有更有效的方法来做它(虽然这些天我打赌编译器会处理转换为一个基于指针的循环为你)。

You need to initialize charcount. Other than that, it should work, provided that z is a zero-terminated array of characters and m is an int or 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).

这里是一个完整的,正确的具有最小编辑的示例:

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 ++;
    }
}

如果您使用 String 某种类的类,而不是一个老式的C null终止的数组,你会想看看这个类如何循环。

If you're using a String class 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.

上面所有的都假设你正在处理ASCII字符串。如果你处理的是UTF编码的字符串,你必须处理多字节字符。

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.

它有很大的区别: scanf 停在第一个空白(我忘记了)。如果你没有正确地声明 z ,它可能会产生更大的不同。 (我还建议在使用 scanf 读取字符串时使用字段宽度[或避免 scanf 完全] ,你不能控制它将尝试存储的字符数,因此理论上 ,没有缓冲区将足够大,以避免溢出更多here: http://www.crasseux.com/books/ctutorial/String-overflows-with-scanf .html

Re your edit: It makes a big difference: scanf will stop on the first blank (I'd forgotten that). It might make an even bigger difference than that, though, if you're not declaring z correctly. (I'd also recommend using a field width when using scanf for reading strings [or avoiding scanf entirely]; 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)

这篇关于计算C中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆