3.编一程序,将两个字符串连接起来,不要用strcat函数。
时间: 2023-12-15 10:49:17 浏览: 39
好的,可以使用以下程序实现:
```c
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i, j;
// 读入两个字符串
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 求出第一个字符串的长度
for (i = 0; str1[i] != '\0'; i++);
// 将第二个字符串添加到第一个字符串的结尾处
for (j = 0; str2[j] != '\0'; j++) {
str1[i + j] = str2[j];
}
// 添加字符串结束标志
str1[i + j] = '\0';
// 输出连接后的字符串
printf("连接后的字符串是:%s\n", str1);
return 0;
}
```
这个程序中,我们使用了两个 for 循环来实现字符串的连接。第一个 for 循环求出了第一个字符串的长度,把指针移动到了第一个字符串的结尾处。然后,第二个 for 循环将第二个字符串的字符复制到第一个字符串的结尾处,并添加字符串结束标志。最后,我们输出了连接后的字符串。
相关问题
编一程序,将两个字符串连接起来,不要用strcat函数
以下是一个简单的程序,用于将两个字符串连接起来,不使用strcat函数:
```c
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i, j;
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
// find the length of the first string
for (i = 0; str1[i] != '\0'; i++);
// concatenate the second string to the end of the first string
for (j = 0; str2[j] != '\0'; j++) {
str1[i + j] = str2[j];
}
// add the null character to the end of the concatenated string
str1[i + j] = '\0';
printf("Concatenated string: %s", str1);
return 0;
}
```
这个程序使用两个字符数组来存储两个输入的字符串,然后使用两个循环来找到第一个字符串的长度和将第二个字符串连接到第一个字符串的末尾。最后,程序添加一个空字符到连接的字符串的末尾,并将其打印出来。
用c语言编一程序,将两个字符串连接起来,不要用strcat函数
以下是使用C语言将两个字符串连接起来的程序,不使用strcat函数:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
int len1, len2;
printf("Enter string 1: ");
gets(str1);
printf("Enter string 2: ");
gets(str2);
len1 = strlen(str1);
len2 = strlen(str2);
for(int i = 0; i < len2; i++) {
str1[len1 + i] = str2[i];
}
printf("Concatenated string: %s\n", str1);
return 0;
}
```
这个程序首先使用gets函数从标准输入中读取两个字符串,然后使用strlen函数计算出两个字符串的长度。接下来使用一个循环将第二个字符串中的每个字符拼接到第一个字符串的末尾。最后输出拼接后的字符串。
需要注意的是,由于使用gets函数存在安全隐患,因此在实际的开发中应该使用更为安全的函数,如fgets。