美文网首页
c 字符串拷贝

c 字符串拷贝

作者: 李永开 | 来源:发表于2021-07-10 17:16 被阅读0次
//
//  main.c
//  cdemo
//
//  Created by liyongkai on 2021/6/6.
//

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>

//使用数组的方式
void copyString01(char *des, const char *source) {

    unsigned long len = strlen(source);
    for (int i = 0; i < len; ++i) {
        char c = source[i];
        des[i] = c;
    }
    des[len] = '\0';
}


//使用指针的方式
void copyString02(char *des, const char *source) {
    
    while (*source != '\0') {
        *des = *source;
        des++;
        source++;
    }
    *des = '\0';
}

//这个有点神奇.  当*source=='\0'并赋值给*des时,相当于把0=0不成立,然后结束循环
void copyString03(char *des, const char *source) {
    while (*des++ = *source++);
}


int main(int argc, const char * argv[]) {
    char *source = "hello world!";
    char buffer[1024] = { 0 };
    
    //copyString01(buffer, source);
//    copyString02(buffer, source);
    copyString03(buffer, source);

    
    printf("%s\n",buffer);
    
    return 0;
}



相关文章

网友评论

      本文标题:c 字符串拷贝

      本文链接:https://www.haomeiwen.com/subject/czcyultx.html