C程序检查子序列
2021-07-07 09:09:13
深夜i
--
--
C
程
序
检
查
子
序
列
检查子序列的C程序; 不要将它与子字符串混淆。 在我们的程序中,我们检查一个字符串是否是另一个字符串的子序列。
用户将输入两个字符串,我们测试其中一个是否是另一个的子序列。 如果第一个字符串是第二个字符串的子序列或第二个字符串是第一个字符串的子序列,则程序打印 yes。 我们首先传递较小长度的字符串,因为我们的函数假设第一个字符串的长度小于或等于第二个字符串的长度。
C子程序
#include <stdio.h>
#include <string.h>
int check_subsequence (char [], char[]);
int main () {
int t;
char s1[1000], s2[1000];
printf("Input first string\n");
gets(s1);
printf("Input second string\n");
gets(s2);
/** Passing smaller length string first */
if (strlen(s1) < strlen(s2))
t = check_subsequence(s1, s2);
else
t = check_subsequence(s2, s1);
if (t)
printf("YES\n");
else
printf("NO\n");
return 0;
}
int check_subsequence (char a[], char b[]) {
int c, d;
c = d = 0;
while (a[c] != '\0') {
while ((a[c] != b[d]) && b[d] != '\0') {
d++;
}
if (b[d] == '\0')
break;
d++;
c++;
}
if (a[c] == '\0')
return 1;
else
return 0;
}
程序的输出:
Input first string
tree
Input second string
Computer science is awesome
YES
函数的逻辑很简单; 如果出现不匹配,我们继续比较两个字符串的字符,然后我们移动到第二个字符串的下一个字符,如果它们匹配,则它们的索引都增加一,并重复该过程。 如果第一个字符串结束,则它是一个子序列,否则不是。
上一篇:
idea打包java可执行jar包
下一篇:
C程序按字母顺序对字符串进行排序
评论区