C语言 计算字符在C中的字符串中出现的次数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7349053/
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
Counting the number of times a character occurs in a string in C
提问by Rob
I'm new to C, and I'm working on my own explodelike function. I'm trying to count how many times a specified character occurs in a string.
我是 C 的新手,我正在开发自己的explode类似函数。我正在尝试计算指定字符在字符串中出现的次数。
int count_chars(char * string, char * chr)
{
int count = 0;
int i;
for (i = 0; i < sizeof(string); i++)
{
if (string[i] == chr)
{
count++;
}
}
return count;
}
It just returns 0 every time. Can anyone explain why, please? :)
它每次只返回 0。谁能解释一下为什么?:)
回答by Jon
Your code is hopelessly flawed. Here's how it shouldlook like:
你的代码有无可救药的缺陷。它应该是这样的:
int count_chars(const char* string, char ch)
{
int count = 0;
int i;
// We are computing the length once at this point
// because it is a relatively lengthy operation,
// and we don't want to have to compute it anew
// every time the i < length condition is checked.
int length = strlen(string);
for (i = 0; i < length; i++)
{
if (string[i] == ch)
{
count++;
}
}
return count;
}
See this code run on example input.
Here's what you are doing wrong:
这是你做错了什么:
- Since you want to find a character, the second parameter should be a character (and not a
char*), This has implications later (see #3). sizeof(string)does not give you the length of the string. It gives the size (in bytes) of a pointer in your architecture, which is a constant number(e.g. 4 on 32-bit systems).- You are comparing some value which is nota memory address to the memory address
chrpoints to. This is comparing apples and oranges, and will always returnfalse, so theifwill never succeed. - What you want to do instead is compare a character(
string[i]) to the second parameter of the function (this is the reason why that one is also achar).
- 因为你想找到一个字符,第二个参数应该是一个字符(而不是一个
char*),这在后面会有影响(见#3)。 sizeof(string)不给你字符串的长度。它给出了体系结构中指针的大小(以字节为单位),它是一个常数(例如,在 32 位系统上为 4)。- 您正在将一些不是内存地址的值与指向的内存地址
chr进行比较。这是比较苹果和橘子,并且总是会返回false,所以if永远不会成功。 - 您想要做的是将字符(
string[i]) 与函数的第二个参数进行比较(这就是为什么那个也是 a 的原因char)。
A "better" version of the above
上面的“更好”版本
Commenters below have correctly identified portions of the original answer which are not the usual way to do things in C, can result in slow code, and possibly in bugs under (admittedly extraordinary) circumstances.
下面的评论者正确识别了原始答案的部分,这些部分不是在 C 中做事的常用方式,可能导致代码缓慢,并且可能在(不可否认的异常)情况下导致错误。
Since I believe that "the" correct implementation of count_charsis probably too involved for someone who is making their first steps in C, I 'll just append it here and leave the initial answer almost intact.
由于我认为对于count_chars在 C 中迈出第一步的人来说,“正确的”实现可能过于复杂,因此我将把它附加到这里并几乎完整地保留最初的答案。
int count_chars(const char* string, char ch)
{
int count = 0;
for(; *string; count += (*string++ == ch)) ;
return count;
}
Note: I have intentionally written the loop this way to make the point that at some stage you have to draw the line between what is possible and what is preferable.
注意:我故意以这种方式编写循环,以表明在某个阶段您必须在可能的和更可取的之间划清界限。
回答by Skizz
This is C! It's designed to be terse!
这是C!它旨在简洁!
int count_chars(const char* string, char ch)
{
int c = 0;
while (*string) c += *(string++) == ch;
return c;
}
Update
更新
I'll try and explain how it works:
我将尝试解释它是如何工作的:
int c = 0;
This will be the count of the number of matches that have been found.
这将是已找到的匹配数的计数。
while (*string)
This is the loop control statement and will continue to iterate the loop as long as the condition is true. In this case the condition is *string. In C, strings are stored 'null terminated' which means the last character of the string is a character with value 0 ('\0'). *stringevaluates to the character the pointer is pointing to. Expressions in C are 'true' if they evaluate to any non-zero value and 'false' if they evaluate to zero. *stringis an expression, so any non-zero character *stringpoints to is true and the '\0' at the end of the string is false. So this will terminate if *stringis pointing to the end of the string.
这是循环控制语句,只要条件为真,就会继续迭代循环。在这种情况下,条件是*string。在 C 中,字符串以“空终止”存储,这意味着字符串的最后一个字符是值为 0 ('\0') 的字符。*string计算指针指向的字符。如果 C 中的表达式计算为任何非零值,则为“真”,如果计算为零,则为“假”。*string是一个表达式,因此任何*string指向的非零字符都为真,字符串末尾的 '\0' 为假。因此,如果*string指向字符串的末尾,这将终止。
*(string++)
This is an expression which evaluates to the value the pointer is pointing at. The ++is a post-increment so the value of the pointer is moved one place forward, i.e. it points to the next character in the string. Note the the value of the expression is not the same as the value of *stringafter the expression has been evaluated because the pointer has moved.
这是一个表达式,其计算结果为指针指向的值。这++是一个后增量,因此指针的值向前移动一个位置,即它指向字符串中的下一个字符。请注意,表达式的值与计算表达式*string后的值不同,因为指针已移动。
*(string++) == ch
This is a comparison expression, it compares the value of *string(before it was updated) to the value of ch. In C, the result of this is an integer (there's no bool type in C) which has the value '1' if the expression is true and '0' if the expression is false.
这是一个比较表达式,它将*string(更新之前)的值与 的值进行比较ch。在 C 中,它的结果是一个整数(C 中没有 bool 类型),如果表达式为真,则值为“1”,如果表达式为假,则值为“0”。
c += *(string++) == ch;
We know the bit after the +=is a '1' if the character is one we're looking for and '0' if not. The +=is shorthand for:
+=如果字符是我们正在寻找的字符,我们知道'1'之后的位是 '0' 如果不是。该+=被简写:
c = c + (*(string++) == ch);
so it will increment the count if a matching character has been found.
因此,如果找到匹配的字符,它将增加计数。
In this particular case, there's little advantage to the +=syntax, but if cwas more complex, say *(variable [index].structure_member [index2])then it would only be evaluated once.
在这种特殊情况下,+=语法没有什么优势,但如果c更复杂,*(variable [index].structure_member [index2])那么它只会被评估一次。
The ;at the end marks the end of the statement and because there's no {after the while, it also marks the end of the whileloop.
将;在年底标志着语句的结束,但由于没有有{后while,这也标志着该结束while循环。
回答by FrustratedWithFormsDesigner
You probably want to use a function that actually gets the length of string, instead of sizeof.
您可能想要使用一个实际获取string, 而不是的长度的函数sizeof。
sizeofwill get the size of the datatype. It will notreturn the length of the string. strlenwill return the length of the string.
sizeof将获得数据类型的大小。它不会返回字符串的长度。strlen将返回字符串的长度。
回答by niko
As everyone told you the answer,
正如每个人都告诉你的答案,
1)you cant use size of but instead strlen(string).They have told you the reason
1)你不能使用大小,而是使用 strlen(string)。他们已经告诉你原因
2)I think everyone missed it here , the second parameter you used is char pointer.but everyone told you to make it as chr but if you want to do it still.
2)我想每个人都在这里错过了它,您使用的第二个参数是字符指针。但是每个人都告诉您将其设置为 chr 但如果您仍然想这样做。
then in the loop it should be
然后在循环中它应该是
if ( string(i)== *chr ) \ not just ch remember you declared it as a pointer
ch gives the address but you want the character so use *ch
You can also use a strchr function.
您还可以使用 strchr 函数。
int count_chars (char *string, char ch)
{
int i;
if(string=strchr(string,'s'))++i;
while (string!=NULL)
if(string=strchr(string+1,chr)
++i;
return i;
}

