C 程序检查子字符串是否存在于字符串中


2022年2月9日, Learn eTutorial
1639

为了更好地理解,我们始终建议您学习下面列出的C语言编程基础主题

如何在字符串中搜索子字符串?

这个 C 程序用于检查字符串是否存在于主字符串中。所以我们需要在主字符串中搜索子字符串的出现。首先,我们必须接受主字符串。保存用户想要搜索的子字符串。

现在检查子字符串是否存在于主字符串中。如果搜索字符串存在,则显示搜索成功;否则,显示搜索不成功。

如何在 C 中实现子字符串搜索?

为了在 C 程序中实现逻辑,首先声明两个字符数组来存储主字符串和搜索字符串。然后我们将初始化两个整数变量来保存字符数组的索引,分别为“count1”和“count2”。然后我们将接受主字符串为“str”,搜索字符串为“search”。

通过使用条件为“str[count1]!=0”的“while 循环”,将“count1”增加 1。当退出循环时,变量“count1”将包含主字符串的长度。使用另一个条件为“search[count2]!=0”的while 循环,将 count2 增加 1。因此,“count2”包含搜索字符串的长度。

使用嵌套的for 循环,我们通过设置标志变量来检查搜索字符串是否在主字符串中。如果“flag=1”,则显示搜索成功。否则,显示搜索不成功。

算法

步骤1:包含头文件以使用C语言程序中的内置函数。

步骤 2: 声明数组“str[80]”、“search[10]”以存储字符串和搜索字符串。

步骤 3: 声明一些整数变量“count1=0count2=0、I、j、flag”。

步骤 4: 从用户读取字符串并将其存储到变量“str”中

步骤 5: 读取用户想要搜索的子字符串并将其存储到变量 Search 中。

步骤 6: 使用条件为“str[count1]!=0”的while 循环,将“count1”增加 1 以获取第一个字符串的长度。

步骤 7: 使用另一个条件为“Search[count2]!=0”的“while 循环”,然后将“count2”增加 1,以获取搜索子字符串的长度。

步骤 8: 使用条件为“i <= count1-count2”的 For 循环执行步骤 9。

步骤 9: 使用另一个for 循环设置“j=1”。

步骤 10: 检查条件“j”。

步骤 11: 如果“str[j]!=search[j-1]”,则设置Flag=0并退出循环。否则将“j”增加 1 并重复步骤 10。

步骤 12: 检查是否“Flag==1”,然后转到步骤 14。

步骤 13: 将“i”增加 1 并重复步骤 8。

步骤 14: 如果“flag=1”,则使用 puts() 函数显示搜索成功,否则显示搜索不成功。

C 语言源代码

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

void main() {
  char str[80], search[10];
  int count1 = 0, count2 = 0, i, j, flag; /* declares the array and variables */
  puts("Enter a string:");
  gets(str);
  puts("Enter search substring:"); /* user enter the string and sub string */
  gets(search);
  while (str[count1] != '\0')
    count1++;
  while (search[count2] != '\0') /* calculating the length of both strings */
    count2++;
  for (i = 0; i <= count1 - count2; i++) {
    for (j = i; j < i + count2; j++) {
      flag = 1;
      if (str[j] != search[j - i]) /* checking each element of the sub string with main string to check for the occurrence of the sub sting */ {
        flag = 0;
        break;
      }
    }
    if (flag == 1) /* prints the result as successful if the flag is one else not successful */
      break;
  }
  if (flag == 1)
    puts("SEARCH SUCCESSFUL!");
  else
    puts("SEARCH UNSUCCESSFUL!");
  getchar();
}
                                      

输出

Enter a string:
Hello how are you?

Enter search substring:
how

SEARCH SUCCESSFUL!