For example, I want to replace abc in 123abc890 with xyz. How would I do this without using #include <string.h>.
I tried attempting this by creating a new string, and with the help of a for loop, I would copy every character into the new string. However, I couldn't seem to find out how to go about doing this. Any method is fine, however I cannot use #include <string.h>.
char str1[] = "123abc890";
char str2[] = "abc";
char str3[] = "xyz";
char new_string[50];
for (int i = 0; str1[i] != '\0'; i++) {
if (str1[i] == str2[i]) {
for (int j = 0; str2[j] != '\0'; j++) {
if (str1[i+j] != str1[i+j]) {
break:
}
new_string[i] = str3[i];
}
}
new_string[i] = str1[i];
}
FYI I am very new to C, so beware of some very clumsy code.
str1andstr2and then returns the first index (if any) instr1that matchesstr2- i.e, basically rewritestrstr.string.hyou can write your own versions of them. Many of them are one or two liners.str1[i] == str2[0]doesn't mean you have a full substring, so if you're going to rush ahead and start copying that substring as if you did, be prepared to undo it when the entire substring doesn't match. Write a helper that checks the full substring match between str2 and str and try it on every index of str1. When it returns true, you're safe to copy str2 over to the destination, else copy str1's character.