20樓 巨大八爪鱼
2015-12-19 10:26
可以用C語言庫函數把insert函數改寫成更簡單且更容易理解的版本: #include <stdio.h> #include <stdlib.h> #include <string.h>
void insert(char *s1, const char *s2) { int len1 = strlen(s1); int len2 = strlen(s2); int pos; char *ch = strchr(s1, *s2); if (ch == NULL) // when not found memcpy(s1 + len1, s2, len2 + 1); // including '\0' at the end else { pos = *ch - *s1; memmove(ch + len2 - 1, ch, len1 - pos + 1); // including '\0' at the end memcpy(ch, s2, len2); } }
int main(int argc, char *argv[]) { char str[50] = "abcdefgh"; char s2[5] = "d45"; insert(str, s2); puts(str); strcpy(str, "abcdef"); strcpy(s2, "45"); insert(str, s2); puts(str); strcpy(str, "definition"); strcpy(s2, "desk"); insert(str, s2); puts(str); return 0; }
|