简体   繁体   English

检查字符串是否是另一个字符串的子字符串

[英]check is string is a substring of another string

如何在不使用substr函数的情况下检查一个字符串是否是C中另一个字符串的子字符串?

You could use the rolling hash method ( Rabin-Karp ), or implement KMP , which is a bit like a state machine. 您可以使用滚动哈希方法( Rabin-Karp ),或实现KMP ,这有点像状态机。

Generally, Rabin-Karp is used when you are searching for multiple target strings, because the second check it requires (for actual equality rather than just hash equality) is well worth it to be able to examine the source string only once. 通常,当您搜索多个目标字符串时,会使用Rabin-Karp,因为它只需要检查一次源字符串就非常值得(对于实际相等性而不仅仅是哈希相等性)进行第二次检查。 In your case, either will do just fine. 就您而言,任何一个都可以。

There is also a more naive solution which is O(n^2) and requires checking for the target string at every position in the source string. 还有一个更幼稚的解决方案,它是O(n ^ 2),并且需要检查源字符串中每个位置的目标字符串。

Don't use substr … use strstr / strnstr ! 不要使用substr …使用strstr / strnstr

Seriously, nothing else will be as fast unless it does exactly the same thing. 认真地讲,除非做完全一样的事情,否则没有其他事情会如此之快。 Why don't you want that? 你为什么不想要那个?

Edit: yeah, there are algorithms with better asymptotic performance. 编辑:是的,有一些算法具有更好的渐近性能。 For text-like searches for a single string, I'd be pretty surprised to see anything outperform a standard library, though. 对于单个字符串的类似文本的搜索,我很惊讶地看到任何东西都超过了标准库。

void main()
{
    char str[80],search[10];
    int count1=0,count2=0,i,j,flag;




    puts("Enter a string:");
    gets(str);

    puts("Enter search substring:");
    gets(search);

    //determines the src length
    while (str[count1]!='\0')
        count1++;
    //determines the key length
    while (search[count2]!='\0')
        count2++;

    for(i=0;i<=count1-count2;i++)
    {
        for(j=i;j<i+count2;j++)
        {
            flag=1;
            if (str[j]!=search[j-i])
            {
                flag=0;
               break;
            }
        }
        if (flag==1)
            break;
    }
    if (flag==1)
        puts("SEARCH SUCCESSFUL!");
    else
        puts("SEARCH UNSUCCESSFUL!");
    getch();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM