C 计算字符串中某个字符出现的次数

发布于 2024-12-03 17:21:55 字数 355 浏览 1 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

淡淡绿茶香 2024-12-10 17:21:58

正如每个人都告诉你答案的那样,

1)你不能使用 size of 而是使用 strlen(string)。他们已经告诉你原因

2)我想每个人都错过了这里,你使用的第二个参数是 char 指针。但是每个人都告诉你将其设置为 chr 但如果您仍想这样做。

那么在循环中应该是

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

您也可以使用 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;
        }

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

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.

   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;
        }
怪我鬧 2024-12-10 17:21:57

你的代码有无可救药的缺陷。它的外观应如下所示:

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

查看在示例输入上运行的代码

这是您做错的地方:

  1. 由于您想查找一个字符,因此第二个参数应该是一个字符(而不是char*),这会在稍后产生影响(请参阅#3)。
  2. sizeof(string) 不会给出字符串的长度。它给出了体系结构中指针的大小(以字节为单位),这是一个常量(例如,32 位系统上为 4)。
  3. 您正在将一些不是内存地址的值与chr指向的内存地址进行比较。这是比较苹果和橙子,并且总是返回 false,因此 if 永远不会成功。
  4. 相反,您想要做的是将字符string[i])与函数的第二个参数进行比较(这就是为什么该参数也是>字符)。

上述评论者的“更好”版本

已经正确识别了原始答案的部分内容,这些部分不是在 C 中执行操作的常用方法,可能会导致代码缓慢,并且可能在(不可否认的特殊情况)情况下出现错误。

因为我相信 count_chars 的“”正确实现对于那些在 C 中迈出第一步的人来说可能太复杂了,所以我将其附加到这里并保持最初的答案几乎完好无损。

int count_chars(const char* string, char ch)
{
    int count = 0;
    for(; *string; count += (*string++ == ch)) ;
    return count;
}

注意:我特意以这种方式编写循环,以表明在某个阶段您必须在可能的情况和最好的情况之间划清界限。

查看此代码在示例输入上运行

Your code is hopelessly flawed. Here's how it should look 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:

  1. Since you want to find a character, the second parameter should be a character (and not a char*), This has implications later (see #3).
  2. 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).
  3. You are comparing some value which is not a memory address to the memory address chr points to. This is comparing apples and oranges, and will always return false, so the if will never succeed.
  4. 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 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.

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.

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.

See this code run on example input.

失去的东西太少 2024-12-10 17:21:57

您可能想要使用实际获取 string 长度的函数,而不是 sizeof

sizeof获取数据类型的大小 。它不会返回字符串的长度。 strlen 将返回字符串的长度。

You probably want to use a function that actually gets the length of string, instead of sizeof.

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.

甜味超标? 2024-12-10 17:21:57

这是C!它被设计得简洁!

int count_chars(const char* string, char ch)
{
  int c = 0;
  while (*string) c += *(string++) == ch;
  return c;
}

更新

我将尝试解释它是如何工作的:

int c = 0;

这将是已找到的匹配数的计数。

while (*string)

这是循环控制语句,只要条件为真就会继续迭代循环。在本例中,条件是*string。在 C 中,字符串以“空终止”方式存储,这意味着字符串的最后一个字符是值为 0 的字符(“\0”)。 *string 计算出指针指向的字符。 C 中的表达式如果计算结果为任何非零值,则为“真”;如果计算结果为零,则为“假”。 *string 是一个表达式,因此 *string 指向的任何非零字符都为 true,字符串末尾的 '\0' 为 false。因此,如果 *string 指向字符串的末尾,这将终止。

*(string++)

这是一个计算结果为指针指向的值的表达式。 ++ 是后递增,因此指针的值向前移动一位,即它指向字符串中的下一个字符。请注意,在计算表达式后,表达式的值与 *string 的值不同,因为指针已移动。

*(string++) == ch

这是一个比较表达式,它将 *string 的值(更新之前)与 ch 的值进行比较。在 C 中,其结果是一个整数(C 中没有 bool 类型),如果表达式为 true,则值为“1”;如果表达式为 false,则值为“0”。

c += *(string++) == ch;

我们知道,如果该字符是我们要查找的字符,则 += 后面的位为“1”,否则为“0”。 += 是:的简写,

c = c + (*(string++) == ch);

因此如果找到匹配的字符,它将增加计数。

在这种特殊情况下,+= 语法几乎没有什么优势,但如果 c 更复杂,比如 *(variable [index].structural_member [index2] ) 那么它只会被评估一次。

末尾的 ; 标记了语句的结束,并且由于 while 后面没有 {,因此它也标记了 的结束> while 循环。

This is C! It's designed to be terse!

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'). *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.

*(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.

*(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.

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:

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 c 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 the while, it also marks the end of the while loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文