【问题标题】:Trying to remove a specific character from a string尝试从字符串中删除特定字符
【发布时间】:2011-10-02 17:28:35
【问题描述】:

我正在尝试编写一个快速函数来删除下划线字符

char yytext[25] = {"IDEN_T3FY_ER"};
char removeUnderscore[9];
int i, j = 0;

printf("Before: %s\n", yytext);


for (i = 0; i < strlen(yytext); i++){
    if (j == 8)
        break;
    if (yytext[i] != '_')
        removeUnderscore[j++] = yytext[i];
}

removeUnderscore[++j] = '\0';

printf("\nAfter: %s", removeUnderscore);

但是在打印时,它将正确获取前 8 个字符并在末尾附加一个垃圾 '8' 值,而不是换行符。

谁能解释为什么?或者也许提供一种更简单的方法?

【问题讨论】:

  • 为什么你的代码中硬编码了 8 和 9 而不是 #define BUFSIZE 8 和 char removeUnderscore[BUFSIZE + 1]; ?另外,为什么要使用 char yytext[25] = {"string"}; ?花括号是不必要的,除非您在代码的其他地方有理由使用它,否则 25 也是不必要的(如果您的字符串更改为超过 25 个字符,则可能有害)。

标签: c string function character


【解决方案1】:

在写入空字符以终止字符串之前,您正在递增索引变量 j。试试:

removeUnderscore[j] = '\0';

改为。

您还说末尾应该有一个换行符,但您从未在输出字符串中写入换行符。

【讨论】:

    【解决方案2】:

    它超过了 removeUnderscore 的大小。最后一行实际上是设置 9 而不是索引 8。

    【讨论】:

      【解决方案3】:
      removeUnderscore[j++] = yytext[i];
      ...
      removeUnderscore[++j] = '\0';
      

      在++j中,j在使用前递增,在j++中,j在使用后递增。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-25
        • 1970-01-01
        • 1970-01-01
        • 2015-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多