没有用C strcat的字符串连接 [英] String concatenation without strcat in C
问题描述
我有使用C麻烦连接字符串,没有strcat的库函数。这里是我的code
I am having trouble concatenating strings in C, without strcat library function. Here is my code
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *a1=(char*)malloc(100);
strcpy(a1,"Vivek");
char *b1=(char*)malloc(100);
strcpy(b1,"Ratnavel");
int i;
int len=strlen(a1);
for(i=0;i<strlen(b1);i++)
{
a1[i+len]=b1[i];
}
a1[i+len]='\0';
printf("\n\n A: %s",a1);
return 0;
}
我做了更正code。这是工作。现在,我可以做没有的strcpy?
I made corrections to the code. This is working. Now can I do it without strcpy?
推荐答案
老回答以下
在声明char数组时,您可以初始化的strcpy
字符串,就像你code,或者直接。
You can initialize a string with strcpy
, like in your code, or directly when declaring the char array.
char a1[100] = "Vivek";
除此之外,你可以做到这一点烧焦逐个字符
Other than that, you can do it char-by-char
a1[0] = 'V';
a1[1] = 'i';
// ...
a1[4] = 'k';
a1[5] = '\0';
或者,你可以写code的几行替换的strcpy
,并使其实现功能或直接在主函数中使用。
Or you can write a few lines of code that replace strcpy
and make them a function or use directly in your main function.
的旧的答案的
您
0 1 2 3 4 5 6 7 8 9 ...
a1 [V|i|v|e|k|0|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_]
b1 [R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_|_|_|_|_|_]
和你想要
0 1 2 3 4 5 6 7 8 9 ...
a1 [V|i|v|e|k|R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_]
所以...
a1[5] = 'R';
a1[6] = 'a';
// ...
a1[12] = 'l';
a1[13] = '\0';
但环之类的东西,对不对? :D
but with loops and stuff, right? :D
试试这个(记得要添加缺少的位)
Try this (remember to add missing bits)
for (aindex = 5; aindex < 14; aindex++) {
a1[aindex] = b1[aindex - 5];
}
现在想想 5
和 14
在上面的循环。
Now think about the 5
and 14
in the loop above.
你能使用替代它们?当你回答这个问题,你解决了,你有编程题:)
What can you replace them with? When you answer this, you have solved the programming problem you have :)
这篇关于没有用C strcat的字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!