1.使用數組下標進行復制
#include<stdio.h> #include<iostream> void copy_string(char str1[], char str2[]) { int i = 0; while (str1[i] != '\0') { str2[i] = str1[i]; i++; } str2[i] = '\0'; } int main() { char str1[] = "hello world"; char str2[30]; copy_string(str1, str2); printf("%s\n",str2); system("pause"); return 0; }
2.使用指針進行復制
#include<stdio.h> #include<iostream> void copy_string2(char* p1, char* p2) { for (; *p1 != '\0'; *p1++,*p2++) { *p2 = *p1; } *p2 = '\0'; } int main() { char* str1 = (char*) "hello world"; char str2[] = "i am a student"; copy_string2(str1, str2); printf("%s\n",str2); system("pause"); return 0; }
需要注意的是:使用指針進行復制時,str必須這樣聲明並初始化:char str2[] = "i am a student";,而不能使用char* str2 = (char*) "i am a student";,因為char* str2實際上是一個常量指針,是不允許修改指針指向的值的,所以會報錯。