例如,我要替换abc
在123abc890
用xyz
。不使用怎么办#include <string.h>
?
我尝试通过创建一个新字符串来尝试进行此操作,并在for循环的帮助下,将每个字符复制到新字符串中。但是,我似乎无法找出执行该操作的方法。任何方法都可以,但是我不能使用#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];
}
仅供参考,我对C还是很陌生,所以请注意一些非常笨拙的代码。
您的代码是一个好的开始,但是有很多问题:
if (str1[i+j] != str1[i+j])
永远是真的这是修改后的版本:
#include <stdio.h>
char *str_replace(char *dest, const char *str1, const char *str2, const char *str3) {
size_t i = 0, j, k = 0;
// replacing substring `str2` with `str3`, assuming sufficient space
while (str1[i] != '\0') {
for (j = 0; str2[j] != '\0'; j++) {
if (str1[i + j] != str2[j]) {
break;
}
}
if (str2[j] == '\0' && j > 0) {
// we have a match: copy the replacement and skip it
i += j;
for (j = 0; str3[j] != '\0'; j++) {
dest[k++] = str3[j];
}
} else {
// copy the byte and skip it.
dest[k++] = str1[i++];
}
}
dest[k] = '\0'; // null terminate the destination
return dest;
}
int main() {
char new_string[50];
printf("%s\n", str_replace(new_string, "123abc890", "abc", "abc"));
printf("%s\n", str_replace(new_string, "123abc890", "abc", "xyz"));
printf("%s\n", str_replace(new_string, "123abc890", "a", "xyz"));
printf("%s\n", str_replace(new_string, "123abc890", "abc", ""));
return 0;
}
输出:
123abc890 123xyz890 123xyzbc890 123890
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句