现在的位置: 首页 > 综合 > 正文

实现C语言的拷贝函数且将复制后的字符串逆序,不能使用库函数,不能定义其他的变量。

2013年10月14日 ⁄ 综合 ⁄ 共 792字 ⁄ 字号 评论关闭
/*
  写C语言的拷贝函数,要求复制字符串,并且将复制后的字符串逆序 比如from中是1234, 
  则to中是4321 void strcyp(char * to,const char * from)问题补充:   
  要求: 不能使用库函数 不能定义其他的变量。
*/
#include <cstdio>
#include <cstdlib>

void strcyp(char *to, const char * from);

int main()
{
    char *in = "asdf!1234+567!@#$%^&*()_+8*90?";
    char *out;
    
    int len = 1;
    char *head;
    
    head = in;
    while (*head != '\0')
    {
        len++;
        head++;
    }
    
    out = (char *)malloc(sizeof(char) * (len + 1));
    strcyp(out, in);

    head = in;
    while (*head != '\0')
      printf("%c", *head++);
    printf("\n");
    
    head = out;
    while (*head != '\0')
      printf("%c", *head++);
    printf("\n");
    
    delete out;
    return 0;
}

void strcyp(char *to, const char * from)
{
    /*特殊情况*/
    if (from == NULL || *from == '\0'|| from == to)
		return -1;
    
    /*首先用to指针指向的当前位置保存from[0]*/  
    *to++ = *from++;
    
    /*定位from到最后一个字符,并且置to数组其余位为-1*/
    while (*from != '\0')
	{
		from++;
		*to++ = -1;
	}
    from--;
	*to-- = '\0';
    
    /*然后用from内元素对所有标记为'-1'位进行填充*/
    while (*to == -1)
		to--;
    
	while (*to != '\0')
		*to++ = *from--;
}

抱歉!评论已关闭.