12th Apr 2024, 11:04 AM
Yaniv B
Yaniv B - avatar
6 Answers
+ 3
It's better to use an array for 'hey' instead of a pointer to a string literal, as string literals should not be modified. Removed the unnecessary 'free' calls as we are not dynamically allocating memory. Simplified the printing of the modified string using 'printf'. Corrected the 'replaceAll' function to replace the 'old' string with the portion of the string after 'old'. This code snippet should work without errors and accomplish the task of replacing the specified substring in the string. I fixed it⤵️ https://sololearn.com/compiler-playground/c0A73FdRGRJT/?ref=app
12th Apr 2024, 12:34 PM
`ᴴᵗᵗየ
`ᴴᵗᵗየ - avatar
+ 2
If you set str[index] = '\0', you would be truncating the str string such that it only contains elements up to the position index. Everything after index in the original string would be deleted or ignored when printing or processing the string further.
12th Apr 2024, 12:53 PM
`ᴴᵗᵗየ
`ᴴᵗᵗየ - avatar
+ 1
In general I tried to see what the result After str[index] = '\0' What happens to string after this ☝️
12th Apr 2024, 12:48 PM
Yaniv B
Yaniv B - avatar
0
#include <stdio.h> #include <stdlib.h> #include <string.h> void replaceAll(char *, const char*); int main() { char *hey = malloc(strlen("hello mf im god here punk") + 1); strcpy(hey, "hello mf im god here punk"); const char *nee = "god"; replaceAll(hey, nee); printf("\n%s\n", hey); free(hey); return 0; } void replaceAll(char *str, const char *old) { char *pos = str; size_t old_len = strlen(old); while ((pos = strstr(pos, old)) != NULL) { memmove(pos, pos + old_len, strlen(pos + old_len) + 1); } } You should use dynamic memory allocation for hey and nee
14th Apr 2024, 2:32 AM
Vidhya Tharan
Vidhya Tharan - avatar
0
replaceAll(hey, nee, ""); if you want to replace use this snippet
14th Apr 2024, 2:34 AM
Vidhya Tharan
Vidhya Tharan - avatar
0
You should check out the line scanf("%d",&n); . The error can be generated by absence of '&' in your scanf line
14th Apr 2024, 10:58 AM
Krish Hasda
Krish Hasda - avatar