从两个字符串中找到匹配的子字符串 [英] Find matching substring from two strings

查看:198
本文介绍了从两个字符串中找到匹配的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我想知道是否有办法在两个字符串中找到匹配的字符串吗?

可以说我有

Hello all,

I am wondering if there is a way to find the piece of matching string in two strings?

Lets say I have

string str1 = "abcdyusdrahhMATCHhyweadh";
string str2 = "hbaiMATCHuncwenckdjrcaae";



那么如何从这些字符串中找到MATCH?

我用MATCH只是为了解释.子字符串可以是任何东西.因此没有要查找的特定字符串.我需要找到最长的匹配子字符串.

谢谢.



So how can I find the MATCH from these strings?

I used MATCH just to explain. The substring can be anything. so there is no particular string to look for. I need to find the longest matching substring.

Thanks.

推荐答案

它称为最长公共子字符串,并且这里有一个C#实现:
It''s called the Longest Common Substring, and there is a C# implementation here: Longest Common Substring[^]


尝试
算法实现/字符串/最长的通用子字符串 [
Try
Algorithm Implementation/Strings/Longest common substring[^]
From reference link :-
public int LongestCommonSubstring(string str1, string str2)
{
        if (String.IsNullOrEmpty(str1) || String.IsNullOrEmpty(str2))
                return 0;

        int[,] num = new int[str1.Length, str2.Length];
        int maxlen = 0;

        for (int i = 0; i < str1.Length; i++)
        {
                for (int j = 0; j < str2.Length; j++)
                {
                        if (str1[i] != str2[j])
                                num[i, j] = 0;
                        else
                        {
                                if ((i == 0) || (j == 0))
                                        num[i, j] = 1;
                                else
                                        num[i, j] = 1 + num[i - 1, j - 1];

                                if (num[i, j] > maxlen)
                                {
                                        maxlen = num[i, j];
                                }
                        }
                }
        }
        return maxlen;


请参阅此
最长连续且最大连续的子字符串 [ http://www.alexandre-gomes.com/?p=177 [
Refer this
The Longest Common Substring with Maximal Consecutive[^]
http://www.alexandre-gomes.com/?p=177[^]


这篇关于从两个字符串中找到匹配的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆