您的位置:首页 > 编程语言 > C语言/C++

C/C++实现strcpy和strcat两个功能

2017-08-05 10:08 225 查看
  strcmp和strcat是string.h头文件中分别实现字符串数组拷贝与拼接功能的函数,详细使用相信大家都了解了,如果还不了解看看实例 C/C++笔试必须熟悉掌握的头文件系列(四)——string.h/cstring就知道怎么使用了。

  下面我们直接来看看具体实现:

 1 strcpy实现 

char* myStrcpy(char* pre, const char* next)
{
if (pre == nullptr || next == nullptr) //空指针直接返回
{
return nullptr;
}
if (pre == next)                       // 两者相等也无需拷贝了
return pre;

while ((*pre++ = *next++) != '\0');    // 依次赋值给主字符数组

return pre;
}


  上面程序实现了strcpy的程序,实现很简单依次赋值给朱字符数组即可,当遇到next指向字符串结束字符’\0’后,完成赋值并且停止赋值。这样新赋值的’\0’就成了字符数组表示的字符串结尾符,哪怕主字符串pre比next长也会戛然而止。字符串判断不管字符数组存了啥,它只认到’\0’前的数是它的主体核心部分。

 2 strcat实现  

char* myStrcat(char* pre, const char* next)
{
if (pre == nullptr || next == nullptr) // 如果有一个为空指针,直接返回pre
return pre;
char* tmp_ptr = pre + strlen(pre); //strlen计算字符数,需要包含都文件string.h,当然也可以自己实现

while ( (*tmp_ptr++ = *next++) != '\0'); // 依次接着赋值

return pre;
}


  上面程序实现了strcat拼接的功能,主要依靠新申请的一个指针先指向主字符数组的尾部,然后依次将另个字符数组字符赋值给后面的空间(可能有些人有疑惑,为什么没有申请额外空间就直接使用后面的空间,实际上这个是简版的写法,所以要求传入指针pre指向的字符数组有足够大的空间,看下面完整程序你就明白了。

 3 主程序 

#include<iostream>
#include<string>
#include<string.h>

using namespace std;

char* myStrcat(char* pre, const char* next)
{
if (pre == nullptr || next == nullptr)
return pre;
char* tmp_ptr = pre + strlen(pre);

while ( (*tmp_ptr++ = *next++) != '\0');

return pre;
}

char* myStrcpy(char* pre, const char* next)
{
if (pre == nullptr || next == nullptr)
{
return nullptr;
}
if (pre == next)
return pre;

while ((*pre++ = *next++) != '\0');

return pre;
}

int main()
{
char str1[100] = "12345";
char str2[20] = "hello world";
myStrcat(str1, str2);
myStrcpy(str1, str2);
printf("%s\n", str1);

return 0;
}


  个人学习记录,由于能力和时间有限,如果有错误望读者纠正,谢谢!

  转载请注明出处:http://blog.csdn.net/FX677588/article/details/76702319
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: