+ 1

delete matching characters from string

Hi everyone, Would someone be able to explain to me why the "if statement" and "s1[k] = '\0';" is necessary in the code. It works fine with just the two for loops. But i dont understand the reason for the if statement and setting "s1[k] to '\0', when i can just add a print statement to the second loop: printf("%c\n", s1[i]; The program below skips over chars from string1 that match any chars from string string2. Appreciate any help. Thank you. void squeeze(char s1[], char s2[]) { int i, j, k; int len1 = strlen(s1); int len2 = strlen(s2); for (i = k = 0; i < len1; i++) { for (j = 0; (s1[i] != s2[j]) && j < len2; j++) ; if (s2[j] == '\0') { s1[k++] = s1[i]; } } s1[k] = '\0'; }

21st Jul 2021, 10:23 PM
David
David - avatar
2 Respostas
+ 4
You can place your printf s1 after "s1[k] = '\0'", because this code find the different character and replace it to the begin of array, so k is the total of different char and '\0' is information of end of array, for example : A = gerrad B = david The result of A will be "gerr" only
22nd Jul 2021, 2:03 AM
Tegar
Tegar - avatar
0
Tegar thank you for answering. I get it now.
22nd Jul 2021, 12:58 PM
David
David - avatar