c語言之利用函數實現字符串的復制


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實際上是一個常量指針,是不允許修改指針指向的值的,所以會報錯。


免責聲明!

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



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