写一个函数将字符串b中的名字,替换到字符串a中的名字,并输出新的字符串a

有一个字符串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 
}

这个函数的逻辑是:

  1. 使用strstr()在字符串a中找到"is"的位置,然后往后偏移3个字符得到名字Lily的起始位置aName。
  2. 使用strtok()从aName中提取出名字Lily。
  3. 使用strtok()从字符串b中提取出名字Wang Wen到bName。
  4. 获取名字Lily和Wang Wen的长度,用memmove()将Wang Wen替换到Lily的位置。
  5. 修改字符串a的结尾使其重新结束。
  6. 返回新的字符串a。

输出结果为:

Student ID 202216264853 is Wang Wen