简体   繁体   中英

Trying to remove a specific character from a string

I'm trying to write a quick function to remove underscore characters

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

However when printing, it will get the first 8 characters correct and append a garbage '8' value at the end, instead of the newline character.

Can anyone explain why? Or perhaps offer an easier way of doing so?

You are incrementing your index variable j before writing the null character to terminate the string. Try:

removeUnderscore[j] = '\0';

instead.

You also say there should be a newline character at the end but you've never written a newline character to the output string.

its overstepping the size of removeUnderscore. that last line is actually setting 9 and not index 8.

removeUnderscore[j++] = yytext[i];
...
removeUnderscore[++j] = '\0';

In ++j j is incremented before being used, and in j++ j is incremented after being used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM