C 计算字符串中某个字符出现的次数
我是 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;
}
每次都只返回0。谁能解释一下为什么吗? :)
I'm new to C, and I'm working on my own explode
like function. I'm trying to count how many times a specified character occurs in a string.
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? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如每个人都告诉你答案的那样,
1)你不能使用 size of 而是使用 strlen(string)。他们已经告诉你原因
2)我想每个人都错过了这里,你使用的第二个参数是 char 指针。但是每个人都告诉你将其设置为 chr 但如果您仍想这样做。
那么在循环中应该是
您也可以使用 strchr 函数。
As everyone told you the answer,
1)you cant use size of but instead strlen(string).They have told you the reason
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.
then in the loop it should be
You can also use a strchr function.
你的代码有无可救药的缺陷。它的外观应如下所示:
查看在示例输入上运行的代码。
这是您做错的地方:
char*
),这会在稍后产生影响(请参阅#3)。sizeof(string)
不会给出字符串的长度。它给出了体系结构中指针的大小(以字节为单位),这是一个常量(例如,32 位系统上为 4)。chr
指向的内存地址进行比较。这是比较苹果和橙子,并且总是返回false
,因此if
永远不会成功。string[i]
)与函数的第二个参数进行比较(这就是为什么该参数也是>字符)。
上述评论者的“更好”版本
已经正确识别了原始答案的部分内容,这些部分不是在 C 中执行操作的常用方法,可能会导致代码缓慢,并且可能在(不可否认的特殊情况)情况下出现错误。
因为我相信
count_chars
的“”正确实现对于那些在 C 中迈出第一步的人来说可能太复杂了,所以我将其附加到这里并保持最初的答案几乎完好无损。注意:我特意以这种方式编写循环,以表明在某个阶段您必须在可能的情况和最好的情况之间划清界限。
查看此代码在示例输入上运行。
Your code is hopelessly flawed. Here's how it should look like:
See this code run on example input.
Here's what you are doing wrong:
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).chr
points to. This is comparing apples and oranges, and will always returnfalse
, so theif
will never succeed.string[i]
) to the second parameter of the function (this is the reason why that one is also achar
).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.
Since I believe that "the" correct implementation of
count_chars
is 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.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.
See this code run on example input.
您可能想要使用实际获取
string
长度的函数,而不是sizeof
。sizeof
将获取数据类型的大小 。它不会返回字符串的长度。strlen
将返回字符串的长度。You probably want to use a function that actually gets the length of
string
, instead ofsizeof
.sizeof
will get the size of the datatype. It will not return the length of the string.strlen
will return the length of the string.这是C!它被设计得简洁!
更新
我将尝试解释它是如何工作的:
这将是已找到的匹配数的计数。
这是循环控制语句,只要条件为真就会继续迭代循环。在本例中,条件是
*string
。在 C 中,字符串以“空终止”方式存储,这意味着字符串的最后一个字符是值为 0 的字符(“\0”)。*string
计算出指针指向的字符。 C 中的表达式如果计算结果为任何非零值,则为“真”;如果计算结果为零,则为“假”。*string
是一个表达式,因此*string
指向的任何非零字符都为 true,字符串末尾的 '\0' 为 false。因此,如果*string
指向字符串的末尾,这将终止。这是一个计算结果为指针指向的值的表达式。
++
是后递增,因此指针的值向前移动一位,即它指向字符串中的下一个字符。请注意,在计算表达式后,表达式的值与 *string 的值不同,因为指针已移动。这是一个比较表达式,它将 *string 的值(更新之前)与
ch
的值进行比较。在 C 中,其结果是一个整数(C 中没有 bool 类型),如果表达式为 true,则值为“1”;如果表达式为 false,则值为“0”。我们知道,如果该字符是我们要查找的字符,则
+=
后面的位为“1”,否则为“0”。+=
是:的简写,因此如果找到匹配的字符,它将增加计数。
在这种特殊情况下,
+=
语法几乎没有什么优势,但如果c
更复杂,比如*(variable [index].structural_member [index2] )
那么它只会被评估一次。末尾的
;
标记了语句的结束,并且由于while
后面没有{
,因此它也标记了的结束> while 循环。
This is C! It's designed to be terse!
Update
I'll try and explain how it works:
This will be the count of the number of matches that have been found.
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').*string
evaluates 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.*string
is an expression, so any non-zero character*string
points to is true and the '\0' at the end of the string is false. So this will terminate if*string
is pointing to the end of the 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*string
after the expression has been evaluated because the pointer has moved.This is a comparison expression, it compares the value of
*string
(before it was updated) to the value ofch
. 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.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: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 ifc
was more complex, say*(variable [index].structure_member [index2])
then it would only be evaluated once.The
;
at the end marks the end of the statement and because there's no{
after thewhile
, it also marks the end of thewhile
loop.