【发布时间】: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