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:
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.