22樓 巨大八爪鱼
2015-12-19 10:41
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」沒必要複製 } }
|