第一種:
#include<stdio.h> #include<iostream> void copy_string(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_string(str1, str2); printf("%s\n",str2); system("pause"); return 0; }
第二種:
#include<stdio.h> #include<iostream> void copy_string(char* p1, char* p2) { while ((*p2 = *p1) != '\0') { *p2++; *p1++; } } int main() { char* str1 = (char*)"hello world"; char str2[] = "i am a student"; copy_string(str1, str2); printf("%s\n", str2); system("pause"); return 0; }
第三種:
#include<stdio.h> #include<iostream> void copy_string(char* p1, char* p2) { //指針運算符比++優先級高 //也就是先將*p1的值給*p2,再進行++操作,i++是先賦值,后自增 while ((*p2++ = *p1++) != '\0') } int main() { char* str1 = (char*)"hello world"; char str2[] = "i am a student"; copy_string(str1, str2); printf("%s\n", str2); system("pause"); return 0; }
第四種:
#include<stdio.h> #include<iostream> void copy_string(char* p1, char* p2) { while (*p1 != '\0') { *p2++ = *p1++; } *p2 = '\0'; } int main() { char* str1 = (char*)"hello world"; char str2[] = "i am a student"; copy_string(str1, str2); printf("%s\n", str2); system("pause"); return 0; }
第五種:
#include<stdio.h> #include<iostream> void copy_string(char* p1, char* p2) { //當*p2++ = *p1++變為0時,就會結束循環 while (*p2++ = *p1++) { ; //'\0' == 0;結束標志 } } int main() { char* str1 = (char*)"hello world"; char str2[] = "i am a student"; copy_string(str1, str2); printf("%s\n", str2); system("pause"); return 0; }
第六種:
#include<stdio.h> #include<iostream> void copy_string(char* p1, char* p2) { for (; *p2++ = *p1++;) { ; //'\0' == 0;結束標志 } } int main() { char* str1 = (char*)"hello world"; char str2[] = "i am a student"; copy_string(str1, str2); printf("%s\n", str2); system("pause"); return 0; }
第七種:
#include<stdio.h> #include<iostream> void copy_string(char str1[], char str2[]) { char* p1, * p2; p1 = str1; p2 = str2; while((*p2++ = *p1++)!='\0') { ; //'\0' == 0;結束標志 } } int main() { char* str1 = (char*)"hello world"; char str2[] = "i am a student"; copy_string(str1, str2); printf("%s\n", str2); system("pause"); return 0; }