前言
接上篇内容,这次会描述字符串的安全追加,建议一样,看懂代码,不要盲目调试,多debug,多查看内存
代码及其解释
#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;
#define SIZE 10
/* 在使用这些函数时,应该加以封装来达到自己想要的效果 */
//dn表示dest“已分配”(可用的)的空间
//如dest[10]="abc";那么它的可用空间应该是10
char* my_strncat(char *dest,const char *source, int dn)
{
int slen = strlen(source);
int dxlen = dn - strlen(dest) - 1;
if (dxlen >= slen)
{
return strncat(dest, source, slen);
}
else
{
return strncat(dest, source, dxlen);
}
return 0;
}
int main()
{
/* 从简单入手 */
/* C CHAR[] TO C CHAR[] */
/* C CHAR*(指向的是常量) TO C CHAR[] */
char cchar1[SIZE] = "abc"; //dest
char cchar2[3] = "de"; //source1
char cchar3[] = "fghiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"; //source2
char *str1 = "jk"; //source3
char *str2 = "lmnoooooooooooooooooooooooooooooooooooo"; //source4
//my_strncat(cchar1, str2, SIZE);
//cout << cchar1 << endl;
/* 在c++字符串中追加字符串*/
string cppstr1 = "123";
string cppstr2 = "555";
//cppstr1.append(cchar2);
//cppstr1.append(str1);
//cppstr1.append(cppstr2);
//cout << cppstr1 << endl;
/* c++字符串追加到字符数组 */
char cchar4[SIZE] = "abcd"; //dest
string cppstr3 = "eturns a pointer to the destination string. No return value is reserved to indicate a"; //source1
string cppstr4 = "et"; //source2
my_strncat(cchar4, cppstr4.c_str(), SIZE);
cout << cchar4 << endl;
system("pause");
return 0;
}
小系列文章小节
一直以为字符串就那么几个函数,玩玩api就好,没想到要注意那么多,之后自己去整理相关内容,一遍遍调试,折腾了挺久的,最终觉得,要处理好字符串和字符数组,主要还是其原理上,然后根据其内存情况来编程,而不能说一步到位,必须视需求来处理