给定两个字符串str1和str2,任务是编写一个C程序来连接这两个字符串,而无需使用strcat()函数
例子:
Input: str1 = "hello", str2 = "world"
Output: helloworld
Input: str1 = "Geeks", str2 = "World"
Output: GeeksWorld
方法:
- 获取要串联的两个字符串
- 声明一个新的字符串以存储串联的字符串
- 插入第一个字符串中的新字符串
- 插入第二个字符串中的新字符串
- 打印连接的字符串
下面是上述方法的实现:
// C Program to concatenate
// two strings without using strcat
#include
int main()
{
// Get the two Strings to be concatenated
char str1[100] = "Geeks", str2[100] = "World";
// Declare a new Strings
// to store the concatenated String
char str3[100];
int i = 0, j = 0;
printf("\nFirst string: %s", str1);
printf("\nSecond string: %s", str2);
// Insert the first string in the new string
while (str1[i] != '\0') {
str3[j] = str1[i];
i++;
j++;
}
// Insert the second string in the new string
i = 0;
while (str2[i] != '\0') {
str3[j] = str2[i];
i++;
j++;
}
str3[j] = '\0';
// Print the concatenated string
printf("\nConcatenated string: %s", str3);
return 0;
}
输出:
First string: Geeks
Second string: World
Concatenated string: GeeksWorld
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。