c語言之利用指針復制字符串的幾種形式


第一種:

#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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM