有一个字符串a,内容为“Student ID 202216264853 is Lily”,另一个字符串b,内容为Wang Wen is my name”。写一个函数将字符串b中的名字,替换到字符串a中的名字,并输出新的字符串a。
https://blog.csdn.net/qq_44452725/article/details/116518295
问题答案由GPT-4Plus模型(语音)与博主程序员之梦@共同编写:
c
char* replaceName(char* a, char* b) {
char* aName = strstr(a, "is") + 3;
aName = strtok(aName, " ");
char* bName = b;
bName = strtok(bName, "is");
int aNameLen = strlen(aName);
int bNameLen = strlen(bName);
memmove(aName, bName, bNameLen);
a[aNameLen + bNameLen - 1] = '\0';
return a;
}
int main() {
char a[] = "Student ID 202216264853 is Lily";
char b[] = "Wang Wen is my name";
char* newStr = replaceName(a, b);
printf("%s\n", newStr);
// Student ID 202216264853 is Wang Wen
}
这个函数的逻辑是:
输出结果为:
Student ID 202216264853 is Wang Wen