#include <stdlib.h>
這句話可以不要
目前共有22篇帖子。
![]() |
回復20樓 @巨大八爪鱼 的內容:可以用C語言庫函數把insert函數改寫成更簡單且更容易理解的版本:
#include <stdio.h> #include <stdlib.h> #incl... #include <stdlib.h>
這句話可以不要 |
![]() |
void insert(char *s1, const char *s2)
{ int len1 = strlen(s1); int len2 = strlen(s2); int pos; char *ch = strchr(s1, *s2); // 在s1中查找s2的第一個字符,返回該字符在s1中的位置地址,如果沒有找到,返回NULL if (ch == NULL) // 如果沒有找到 memcpy(s1 + len1, s2, len2 + 1); // 直接把s2字符串連同末尾的\0一起複製到s1[len1]處,也就是s1的字符串結尾處(\0處) else { // 以abcdef, d45為例 pos = *ch - *s1; // 計算找到的字符d在s1中的位置(數字,從0開始),計算結果為3 memmove(ch + len2 - 1, ch, len1 - pos + 1); // 移動字符串空出空間。把def\0向右移動len2-1個位置(也就是2個位置),共移動len1 - pos + 1個字節,也就是4個字節。 memcpy(ch, s2, len2); // 複製字符串。把d45(不含末尾的\0)複製到abc[ded]ef的[ded]處覆蓋掉。 // 其實程序在這裏還可以進行修改。因為字符「d」沒必要複製 } } |