C语言编写程序,定义任意两个字符串数据,将两个字符串连接起来,不要用strcat 函数,结果输出到屏幕查看结果
时间: 2023-06-14 19:02:56 浏览: 52
可以使用指针和循环实现字符串连接,示例代码如下:
```c
#include <stdio.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
char result[100]; // 存储结果的字符串数组,需要预设足够的长度
int i, j;
// 将 str1 复制到 result 中
for (i = 0; str1[i] != '\0'; i++) {
result[i] = str1[i];
}
// 将 str2 连接到 result 后面
for (j = 0; str2[j] != '\0'; j++) {
result[i + j] = str2[j];
}
result[i + j] = '\0'; // 结尾要加上字符串结束符
// 输出结果
printf("%s\n", result);
return 0;
}
```
输出结果为:
```
HelloWorld
```
相关问题
用C语言编写程序,将两个字符串连接起来,不要用strcat函数
可以用指针来实现字符串连接。
以下是一个简单的例子:
```c
#include <stdio.h>
void mystrcat(char *dest, const char *src) {
// 将 dest 指针移动到字符串末尾
while (*dest != '\0') {
dest++;
}
// 将 src 复制到 dest 的末尾
while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
// 将字符串结束符添加到 dest 的末尾
*dest = '\0';
}
int main() {
char str1[100] = "Hello, ";
char str2[] = "world!";
mystrcat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
输出:
```
Hello, world!
```
在上面的代码中,`mystrcat` 函数将 `src` 指向的字符串追加到 `dest` 指向的字符串的末尾。首先,它将 `dest` 指针移动到字符串末尾,然后将 `src` 复制到 `dest` 的末尾,最后添加字符串结束符到 `dest` 的末尾。
使用C语言编写一个程序,将两个字符串连接起来,不要用strcat函数
好的,以下是使用C语言编写的将两个字符串连接起来的程序,不使用strcat函数:
```c
#include <stdio.h>
#include <string.h>
void my_strcat(char *s1, char *s2) {
while (*s1) {
s1++;
}
while (*s2) {
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0';
}
int main() {
char str1[50], str2[50];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
my_strcat(str1, str2);
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
在这个程序中,我们定义了一个名为`my_strcat`的函数,它接受两个指向字符数组的指针作为参数,将第二个字符串连接到第一个字符串的末尾。具体实现如下:
- 使用一个while循环找到第一个字符串的末尾。
- 然后使用另一个while循环将第二个字符串的每个字符复制到第一个字符串的末尾。
- 最后将第一个字符串的末尾设置为'\0'。
在主函数中,我们首先从用户那里获取两个字符串,然后调用`my_strcat`函数将它们连接起来,最后输出结果。
需要注意的是,这个程序假设两个字符串都是以'\0'结尾的。如果不是,可能会导致程序崩溃或产生意外结果。所以,实际应用中还需要对输入进行有效性判断。