解决方法如下所示:
String str = "Hello, world!";
str.replace("world", "Arduino");
Serial.println(str);
上述代码会将字符串中的"world"替换为"Arduino",并将结果打印到串口。
#include
void myReplace(char* str, const char* oldStr, const char* newStr) {
char* pos = strstr(str, oldStr);
if (pos != NULL) {
int oldStrLen = strlen(oldStr);
int newStrLen = strlen(newStr);
int tailLen = strlen(pos + oldStrLen);
memmove(pos + newStrLen, pos + oldStrLen, tailLen + 1);
memcpy(pos, newStr, newStrLen);
}
}
char str[] = "Hello, world!";
myReplace(str, "world", "Arduino");
Serial.println(str);
上述代码定义了一个自定义的myReplace函数,用于替换字符数组中的字符串。函数使用了C语言的标准库函数strstr、strlen、memmove和memcpy来实现替换操作。最后,将结果打印到串口。
请注意,在使用自定义的replace函数时,确保目标字符数组有足够的空间来存储替换后的字符串。