【问题标题】:Comparing every char in a string to a constant将字符串中的每个字符与常量进行比较
【发布时间】:2021-04-30 14:53:45
【问题描述】:

抱歉,我对 c 比较陌生。我想要做的是遍历一个字符串并将字符串中的每个字符与一个字符进行比较。如果成功,我会打印一些值。但是我遇到了分段错误。

我的代码:

int i;
const char* perc = '%';
char mystr[7] = "hell%o";

for(i=0;i<sizeof(mystr);i++){
        if(strcmp(mystr[i],perc)!=0){
            printf("%d",i);
        }

注意:我在这里没有使用 % 格式字符串,我只是在寻找它在字符串中的位置。

谢谢。

【问题讨论】:

  • strcmp() 采用指向以空字符结尾的字符串的指针。单个字符不是那样的。只需将perc 声明为char 并检查mystr[i] == perc 是否。
  • const char* perc = '%';
  • 提示:使用-Wall 编译并注意警告
  • 我实际上只是在寻找它在字符串中的位置。听起来你想要strchr()
  • 您可能想否定比较。

标签: c strcmp


【解决方案1】:

strcmp() 用于比较字符串。要比较字符,可以使用== 运算符。

还请注意,sizeof 不是用于获取字符串的长度,而是用于获取用于该类型的字节数。在这种情况下,它用于char 数组,因此它可以根据您想要做的工作,因为sizeof(char) 被定义为1,因此字节数将等于元素数。请注意,终止的空字符和之后的未使用元素将添加到计数中(如果它们存在)。要获取字符串的长度,您应该使用strlen() 函数。

int i;
const char perc = '%'; /* use char, not char* */
char mystr[7] = "hell%o";
int len = strlen(mystr); /* use strlen() to get the length of the string */

for(i=0;i<len;i++){
        if(mystr[i] != perc){ /* compare characters */
            printf("%d",i);
        }

【讨论】:

    【解决方案2】:

    if(strcmp(mystr[i],perc)!=0){

    必须是if(mystr[i]!= perc){。而const char* perc = '%'; 应该是const char perc = '%';

    strcmp 接受两个字符串 (char*),但您传递的是字符。用 gcc 和-Wall 编译显示:

    c.c: In function ‘main’:
    c.c:5:20: warning: initialization of ‘const char *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]
        5 | const char* perc = '%';
          |                    ^~~
    c.c:9:24: warning: passing argument 1 of ‘strcmp’ makes pointer from integer without a cast [-Wint-conversion]
        9 |         if(strcmp(mystr[i],perc)!=0){
          |                   ~~~~~^~~
          |                        |
          |                        char
    In file included from c.c:1:
    /usr/include/string.h:137:32: note: expected ‘const char *’ but argument is of type ‘char’
      137 | extern int strcmp (const char *__s1, const char *__s2)
          |                    ~~~~~~~~~~~~^~~~
    

    永远记住:编译器是你最好的朋友之一。

    固定程序可以是:

    #include <stdio.h>
    #include <string.h>
    int main() {
      int i;
      const char perc = '%';
      char mystr[7] = "hell%o";
    
      for (i = 0; i < sizeof(mystr); i++) {
        if (mystr[i] != perc) {
          printf("%d", i);
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多