华为面试题解析 - 03

    03. 编程实现strcpy


    我们知道strcpy是字符串复制函数。

    定义于:

string.h

    声明:

char *strcpy(char *dest, const char *src);

   原型:

#ifdef _NC_RESTRICT
char *strcpy(char *restrict dest, const char *restrict src)
#else
char *strcpy(char *dest, const char* src)
#endif
{
    char *ret = dest;
    while (*dest++ = *src++)
        ;
    return ret;
}

    

    1. 使用strlen实现

/*
 * exercise01.c
 *
 *  Created on: 2012-11-5
 *      Author: xiaobin
 *
 *      Huawei face questions
 */

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

char *strcpy1(char *dest, const char *src)
{

	char *ret = dest;
	int len = strlen(src);

	int i = 0;
	while (len-- != 0) {
	    ret[i] = src[i];
	    i++;
	}

	return ret;
}


int main(int argc, char* argv[])
{
	char *s = "hello,world";
	char *d;
	strcpy1(d, s);
	printf("%s\n", d);
	return 0;
}

    计算源串的长度,然后循环赋值。

    

    2. 无strlen实现

/*
 * exercise01.c
 *
 *  Created on: 2012-11-5
 *      Author: xiaobin
 *
 *      Huawei face questions
 */

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

char *strcpy1(char *dest, const char *src)
{

	char *ret = dest;

	int i = 0;
	while (*src != 0) {
	    ret[i] = *src;
	    i++;
	    *src++;
	}

	return ret;
}


int main(int argc, char* argv[])
{
	char *s = "hello,world";
	char *d;
	strcpy1(d, s);
	printf("%s\n", d);
	return 0;
}


参考文章:http://clc-wiki.net/wiki/C_standard_library:string.h:strcpy

你可能感兴趣的:(华为面试题解析 - 03)