C语言编程题目?

编写一个函数,利用指针将输入的两个字符串s1和s2连接起来,要求短的在前。

要求:

1、使用子函数 char *StrCat(char *s,char *t)

2、不能使用字符串函数strcat

【输入形式】

从键盘输入两字符串,输入一个字符串后回车,再输入 另外一个。

【输出形式】

输出连接后的字符串

【样例输入】

示例1:

abcde

kobe

示例2:

123

456

【样例输出】

示例1:

kobeabcde

示例2:

123456

下面是一个可以利用指针将两个字符串连接起来的 C 语言程序。该程序定义了一个子函数 `StrCat`,用于将两个字符串连接起来,并返回连接后的结果。主函数中,我们先从标准输入读入两个字符串,然后根据它们的长度调用 `StrCat` 函数,将它们连接起来并输出结果。

```c
#include <stdio.h>
#include <string.h>

#define MAX_LEN 100

char* StrCat(char* s, char* t);

int main() {
char s1[MAX_LEN], s2[MAX_LEN];

// 从标准输入读入两个字符串
printf("请输入第一个字符串:");
fgets(s1, MAX_LEN, stdin);
printf("请输入第二个字符串:");
fgets(s2, MAX_LEN, stdin);

// 将短的字符串放在前面,然后连接两个字符串
if (strlen(s1) > strlen(s2)) {
char *t = s1;
s1 = s2;
s2 = t;
}
StrCat(s1, s2);

// 输出结果
printf("连接后的字符串为:%s", s1);

return 0;
}

char* StrCat(char* s, char* t) {
int i, j;

// 找到 s 末尾位置
for (i = 0; s[i] != '\0'; i++);

// 将 t 中的字符复制到 s 的末尾
for (j = 0; t[j] != '\0'; j++) {
s[i + j] = t[j];
}
s[i + j] = '\0';

return s;
}
```

在这个程序中,我们首先定义了子函数 `StrCat`,该函数接受两个指向字符数组的指针 `s` 和 `t`,将 `t` 中的字符连接到 `s` 的末尾,并返回连接后的结果。具体来说,我们首先找到 `s` 的末尾位置,然后使用循环遍历 `t` 中的每个字符,并将它们复制到 `s` 的末尾。

在主函数中,我们先从标准输入读入两个字符串,并使用 `strlen` 函数获取它们的长度。然后,我们判断哪个字符串比较短,将其放在前面,并调用 `StrCat` 函数将两个字符串连接起来。最后,我们使用 `printf` 函数输出连接后的字符串。

需要注意的是,在函数 `StrCat` 中,我们没有对输入数据进行任何检查(例如,字符串的长度是否超过了数组的大小等)。如果需要确保输入数据的有效性,可以在程序中添加相应的检查代码。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-06-04
#include <stdio.h>
char *StrCat(char *s,char *t)
{
int i=0,j=0;
char *s1,*t1;
s1=s;t1=t;
for(;*s1;s1++,i++);
for(;*t1;t1++,j++);
if(i<=j)
{
for(;*t;)*s1++=*t++;*s1='\0';
return s;
}
else
{
for(;*s;)*t1++=*s++;*t1='\0';
return t;
}
}

int main(int argc, char *argv[])
{
char a[100],b[100];
scanf("%s",a);
scanf("%s",b);
printf("%s",StrCat(a,b));
return 0;
}
相似回答