[英]Add 2 chars without using strncpy?
如何不使用strncpy
函数手动连接两个char数组?
我可以说char1 + char2
吗?
还是我必须编写一个for
循环来获取单个元素并像这样添加它们:
addchar[0] = char1[0];
addchar[1] = char1[1];
etc
etc
addchar[n] = char2[0];
addchar[n+1] = char2[1];
etc
etc
要澄清一下,如果char1 =“ happy” char2 =“ birthday”
我要添加字符= happybirthday
对于仅C解决方案,请使用strncat :
char destination[80] = "";
char string1[] = "Hello";
char string2[] = " World!";
/* Copy string1 to destination */
strncat(destination, string1, sizeof(destination));
/* Append string2 to destination */
strncat(destination, string2, sizeof(destination) - sizeof(string1));
请注意,字符串函数strn *系列比没有n的函数更安全,因为它们避免了缓冲区溢出的可能性。
对于C ++解决方案,只需使用std :: string和operator +或operator + =:
std::string destination("Hello ");
destination += "World";
destination += '!';
如果您使用的是c ++,则只需使用std::string
。 使用std::string
s,支持+
运算符,因此您可以执行string1 + string2。
如果您认为两个琐碎的循环是“手动”的,那么是的,不使用标准库,这是唯一的方法。
char *append(const char *a, const char *b) {
int i = 0;
size_t na = strlen(a);
size_t nb = strlen(b);
char *r = (char*)calloc(na + nb + 1, 1);
for (i = 0; i < na; i++) {
r[i] = a[i];
}
for (i = 0; i < nb; i++) {
r[na + i] = b[i];
}
return r;
}
记住要打free
电话。
在不使用库函数的情况下,以下是步骤:
1.指向string1中的第一个字符。
2.当指针上的当前字符不为null时,增加指针。
3.创建一个指向string2的“源”指针。
4.虽然“源”位置处的字符不为空:
4.1。 将字符从“源”位置复制到String1指针指向的位置。
4.2。 递增两个指针。
除非这是家庭作业,否则请使用C ++ std::string
作为文本。
如果必须使用C样式字符串,请使用库函数。
库功能经过优化和验证,减少了开发时间。
好了,您想要这样的东西:
char1 + char2
首先,让我们看一下疯狂的解决方案:
C:
char* StringAdd(char* a_Left, char* a_Right)
{
unsigned int length_left = strlen(a_Left);
unsigned int length_right = strlen(a_Right);
unsigned int length = length_left + length_right;
char* result = (char*)malloc(length);
// clear the string
memset(result, 0, length);
// copy the left part to the final string
memcpy(result, a_Left, length_left);
// append the right part the to the final string
memcpy(&result[length_left], a_Right, length_right);
// make sure the string actually ends
result[length] = 0;
return result;
}
C ++:
char* StringAdd(char* a_Left, char* a_Right)
{
unsigned int length_left = strlen(a_Left);
unsigned int length_right = strlen(a_Right);
unsigned int length = length_left + length_right;
char* result = new char[length];
// clear the string
memset(result, 0, length);
// copy the left part to the final string
memcpy(result, a_Left, length_left);
// append the right part the to the final string
memcpy(&result[length_left], a_Right, length_right);
// make sure the string actually ends
result[length] = 0;
return result;
}
现在,让我们看看理智的解决方案:
char* StringAdd(char* a_Left, char* a_Right)
{
unsigned int length = strlen(a_Left) + strlen(a_Right);
char* result = new char[length];
strcpy(result, a_Left);
strcat(result, a_Right);
return result;
}
那么,这是家庭作业吗? 我不在乎
如果是这样,问自己:您学到了什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.