如何检查字符串是否包含C#中另一个字符串的某些部分?

时间:2016-04-10 06:01:10

标签: c# string

true

如果String1包含String2的某些部分,我想返回String1.Contains(String2)。在这个例子中,String2有“12”,它存在于String1中。因此,例如true应该返回'Contains'

如何制作此typedef int *pInt; //Each element of arr is a int-type pointer pInt arr[5] = {a, b, c, d, e}; int matrix[5][5] = {0}; for(int i = 0; i < 5; ++i){ for(int j = 0 ; j < 5; ++j){ matrix[i][j] = arr[j][i]; } } 功能?

5 个答案:

答案 0 :(得分:6)

您尚未告诉我们匹配字符串的最小长度,因此我假设最小长度为1

因此,你可以写:

String1.Any(c => String2.Contains(c))

答案 1 :(得分:3)

另一种选择是使用Intersect。这将帮助您设置某些&#34;阈值&#34;类似元素的数量:

string String1 = "12345"
string String2 = "12abc"

var result = String1.ToCharArray().Intersect(String2.ToCharArray()).ToList();

if (result.Count > 0) //to check if there is any intersect

只需更改&gt; 0到&gt; N(N是正整数:1,2,3,......等)来设置阈值。

答案 2 :(得分:2)

如果要更改两个字符串中必须包含的最小字符数,可以执行以下操作。将charsToCompare常量更改为要工作的最小共享值数。

using System;

public class Program
{
   public static void Main()
   {
      Console.WriteLine("Hello World".ContainsSubstring("Henry"));
      Console.WriteLine("Hello World".ContainsSubstring("Hank"));
      Console.WriteLine("12345".ContainsSubstring("12abc"));
   }
}

public static class MyExtensions
{
   public static bool ContainsSubstring(this string str, string compareValue)
   {
      const int charsToCompare = 2;
      var subString = compareValue.Substring(0, Math.Min(charsToCompare, compareValue.Length));
      if (str.Contains(subString))
      {
         return true;
      }
      else if (compareValue.Length > charsToCompare)
      {
         return str.ContainsSubstring(compareValue.Substring(1));
      }
      return false;
   }
}

你可以在dotnetfiddle https://dotnetfiddle.net/Ie1eLx

上玩它

答案 3 :(得分:2)

您可以使用这种方式检查两个字符串之间是否存在公共子字符串

public static bool IsPresent(string str1, string str2)
        {

            int[,] num = new int[str1.Length, str2.Length];
            int maxLen = 0;
            int lastSubsBegin = 0;
            StringBuilder sequenceBuilder = new StringBuilder();

            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];
                            int thisSubsBegin = i - num[i, j] + 1;
                            if (lastSubsBegin == thisSubsBegin)
                            {
                                // If the current LCS is the same as the last time this block ran
                                sequenceBuilder.Append(str1[i]);
                            }
                            else
                            {
                                // Reset the string builder if a different LCS is found
                                lastSubsBegin = thisSubsBegin;
                                sequenceBuilder.Length = 0;
                                sequenceBuilder.Append(str1.Substring(lastSubsBegin, (i + 1) - lastSubsBegin));
                            }
                        }
                    }
                }
            }

            if (sequenceBuilder.Length != 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

这是有用的链接 http://www.datavoila.com/projects/text/longest-common-substring-of-two-strings.html

答案 4 :(得分:1)

您可以检查此处列出的levenshtein距离:[http://social.technet.microsoft.com/wiki/contents/articles/26805.c-calculating-percentage-similarity-of-2-strings.aspx]

根据您希望字符串的相似程度,您可以更改对CalculateSimilarity的检查。

bool AreSimilar(string a, string b)
{
    return CalculateSimilarity(a, b) > .25;
}

/// <summary>
/// Calculate percentage similarity of two strings
/// <param name="source">Source String to Compare with</param>
/// <param name="target">Targeted String to Compare</param>
/// <returns>Return Similarity between two strings from 0 to 1.0</returns>
/// </summary>
double CalculateSimilarity(string source, string target)
{
    if ((source == null) || (target == null)) return 0.0;
    if ((source.Length == 0) || (target.Length == 0)) return 0.0;
    if (source == target) return 1.0;

    int stepsToSame = ComputeLevenshteinDistance(source, target);
    return (1.0 - ((double)stepsToSame / (double)Math.Max(source.Length, target.Length)));
}

/// <summary>
/// Returns the number of steps required to transform the source string
/// into the target string.
/// </summary>
int ComputeLevenshteinDistance(string source, string target)
{
    if ((source == null) || (target == null)) return 0;
    if ((source.Length == 0) || (target.Length == 0)) return 0;
    if (source == target) return source.Length;

    int sourceWordCount = source.Length;
    int targetWordCount = target.Length;

    // Step 1
    if (sourceWordCount == 0)
        return targetWordCount;

    if (targetWordCount == 0)
        return sourceWordCount;

    int[,] distance = new int[sourceWordCount + 1, targetWordCount + 1];

    // Step 2
    for (int i = 0; i <= sourceWordCount; distance[i, 0] = i++) ;
    for (int j = 0; j <= targetWordCount; distance[0, j] = j++) ;

    for (int i = 1; i <= sourceWordCount; i++)
    {
        for (int j = 1; j <= targetWordCount; j++)
        {
            // Step 3
            int cost = (target[j - 1] == source[i - 1]) ? 0 : 1;

            // Step 4
            distance[i, j] = Math.Min(Math.Min(distance[i - 1, j] + 1, distance[i, j - 1] + 1), distance[i - 1, j - 1] + cost);
        }
    }

    return distance[sourceWordCount, targetWordCount];
}