C语言编程:【样例输入】 abcdef def aaa 【样例输出】 please input 3 strings as MainStr , SubStr1 and SubStr2 MainStr =:6,a,b,c,d,e,f, SubStr1 =:3,d,e,f, SubStr2 =:3,a,a,a, SubStr1 compare with SubStr2 is 1 pos of SubStr1 in MainStr is 4 pos of SubStr2 in MainStr
时间: 2024-03-03 08:51:44 浏览: 187
这是一个字符串匹配的问题,需要编写 C 语言程序。下面是代码示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char MainStr[100], SubStr1[100], SubStr2[100];
int i, j, len1, len2, len3, pos1 = -1, pos2 = -1, flag = 0;
printf("please input 3 strings as MainStr , SubStr1 and SubStr2\n");
scanf("%s%s%s", MainStr, SubStr1, SubStr2);
len1 = strlen(MainStr);
len2 = strlen(SubStr1);
len3 = strlen(SubStr2);
printf("MainStr =:%d,", len1);
for (i = 0; i < len1; i++) {
printf("%c,", MainStr[i]);
}
printf(" SubStr1 =:%d,", len2);
for (i = 0; i < len2; i++) {
printf("%c,", SubStr1[i]);
}
printf(" SubStr2 =:%d,", len3);
for (i = 0; i < len3; i++) {
printf("%c,", SubStr2[i]);
}
printf("\n");
for (i = 0; i <= len1 - len2; i++) {
flag = 1;
for (j = 0; j < len2; j++) {
if (MainStr[i+j] != SubStr1[j]) {
flag = 0;
break;
}
}
if (flag == 1) {
pos1 = i + 1;
break;
}
}
flag = 0;
for (i = 0; i <= len1 - len3; i++) {
flag = 1;
for (j = 0; j < len3; j++) {
if (MainStr[i+j] != SubStr2[j]) {
flag = 0;
break;
}
}
if (flag == 1) {
pos2 = i + 1;
break;
}
}
if (strcmp(SubStr1, SubStr2) == 0) {
printf("SubStr1 compare with SubStr2 is 1\n");
} else {
printf("SubStr1 compare with SubStr2 is 0\n");
}
if (pos1 != -1) {
printf("pos of SubStr1 in MainStr is %d\n", pos1);
} else {
printf("SubStr1 not found in MainStr\n");
}
if (pos2 != -1) {
printf("pos of SubStr2 in MainStr is %d\n", pos2);
} else {
printf("SubStr2 not found in MainStr\n");
}
return 0;
}
```
程序实现了对三个字符串的输入,输出三个字符串的长度和内容。然后分别在 MainStr 中查找 SubStr1 和 SubStr2,输出它们在 MainStr 中的位置或者未找到的提示。最后比较 SubStr1 和 SubStr2 是否相同,输出比较结果。
阅读全文