[英]How to check if a string contains some part of another string in C#?
String1 = "12345"
String2 = "12abc"
我想回到true
,如果String1
包含的某些部分String2
。 在這個例子中,String2有“12”,它存在於String1中。 所以例如String1.Contains(String2)
應該返回true
。
我怎樣才能制作這樣的'Contains'
功能?
你沒有告訴我們匹配字符串的最小長度,所以我假設最小長度為1
。
因此,你可以寫:
String1.Any(c => String2.Contains(c))
另一種選擇是使用Intersect。 這將幫助您設置類似元素數量的某個“閾值”:
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
只需將> 0更改為> N(N為正整數:1,2,3,...等)即可設置閾值。
你可以做到這一點。
string String1 = "12345";
string String2 = "12abc";
var subs = from i in Enumerable.Range(0, String2.Length)
from l in Enumerable.Range(1, String2.Length - i)
let part = String2.Substring(i, l)
select part;
if(subs.Any(s=> String1.Contains(s)))
{
// contains.
}
這是有效點(來自評論),即使單個字符也可以匹配兩個字符串。
if(String1.Any(s=>String2.Contains(s)))
{
// contains
}
您可以使用IndexOfAny:
string string1 = "12345";
string string2 = "12abc";
var isFound = string1.IndexOfAny(string2.ToCharArray()) >= 0;
var firstOccurrenceIdx = string1.IndexOfAny(string2.ToCharArray());
如果您要更改兩個字符串中必須包含的最小字符數,則可以執行以下操作。 將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上玩它
您可以使用這種方式檢查兩個字符串之間是否存在公共子字符串
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
您可以檢查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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.