我想使用C#检查字符串值是否在字符串数组中包含单词。例如,
string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext", etc... };
if(stringToCheck.contains stringArray) //one of the items?
{
}
如何检查'stringToCheck'的字符串值在数组中是否包含单词?
我想使用C#检查字符串值是否在字符串数组中包含单词。例如,
string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext", etc... };
if(stringToCheck.contains stringArray) //one of the items?
{
}
如何检查'stringToCheck'的字符串值在数组中是否包含单词?
Answers:
您可以按照以下方法进行操作:
string stringToCheck = "text1";
string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };
foreach (string x in stringArray)
{
if (stringToCheck.Contains(x))
{
// Process...
}
}
更新:可能是您正在寻找更好的解决方案。.请参阅下面的@Anton Gogolev的答案,该答案使用了LINQ。
就是这样:
if(stringArray.Any(stringToCheck.Contains))
/* or a bit longer: (stringArray.Any(s => stringToCheck.Contains(s))) */
这将检查是否stringToCheck
包含来自的子字符串中的任何一个stringArray
。如果要确保它包含所有子字符串,请更改Any
为All
:
if(stringArray.All(stringToCheck.Contains))
stringArray.Any(s => s.IndexOf(stringToCheck, StringComparison.CurrentCultureIgnoreCase) > -1)
无需使用LINQ
if (Array.IndexOf(array, Value) >= 0)
{
//Your stuff goes here
}
stringArray.Any(w => stringToCheck.IndexOf(w) >= 0)
但是使用String.Contains的Linq答案更有意义,因为这正是所要的。
只需使用linq方法:
stringArray.Contains(stringToCheck)
using System.Linq;
最简单的示例方式。
bool bol=Array.Exists(stringarray,E => E == stringtocheck);
string strName = "vernie";
string[] strNamesArray = { "roger", "vernie", "joel" };
if (strNamesArray.Any(x => x == strName))
{
// do some action here if true...
}
大概是这样的:
string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };
if (Array.Exists<string>(stringArray, (Predicate<string>)delegate(string s) {
return stringToCheck.IndexOf(s, StringComparison.OrdinalIgnoreCase) > -1; })) {
Console.WriteLine("Found!");
}
String.Contains
可能比String.IndexOf
除非您不想忽略大小写要好,因为Microsoft忘记了两个参数,String.Contains
您必须编写自己的参数。考虑:Array.Exists(stringArray, s => stringToCheck.IndexOf(s, StringComparison.OrdinalIgnoreCase) > -1)
您可以定义自己的string.ContainsAny()
和string.ContainsAll()
方法。另外,我什至抛出了string.Contains()
一种允许不区分大小写的比较的方法,等等。
public static class Extensions
{
public static bool Contains(this string source, string value, StringComparison comp)
{
return source.IndexOf(value, comp) > -1;
}
public static bool ContainsAny(this string source, IEnumerable<string> values, StringComparison comp = StringComparison.CurrentCulture)
{
return values.Any(value => source.Contains(value, comp));
}
public static bool ContainsAll(this string source, IEnumerable<string> values, StringComparison comp = StringComparison.CurrentCulture)
{
return values.All(value => source.Contains(value, comp));
}
}
您可以使用以下代码进行测试:
public static void TestExtensions()
{
string[] searchTerms = { "FOO", "BAR" };
string[] documents = {
"Hello foo bar",
"Hello foo",
"Hello"
};
foreach (var document in documents)
{
Console.WriteLine("Testing: {0}", document);
Console.WriteLine("ContainsAny: {0}", document.ContainsAny(searchTerms, StringComparison.OrdinalIgnoreCase));
Console.WriteLine("ContainsAll: {0}", document.ContainsAll(searchTerms, StringComparison.OrdinalIgnoreCase));
Console.WriteLine();
}
}
你也可以做同样的事情,安东Gogolev建议检查是否任何项目在stringArray1
比赛的任何项目在stringArray2
:
if(stringArray1.Any(stringArray2.Contains))
同样,stringArray1中的所有项目都与stringArray2中的所有项目匹配:
if(stringArray1.All(stringArray2.Contains))
我使用了与Maitrey684的IndexOf和Theomax的foreach循环类似的方法来创建它。(注意:前3个“字符串”行只是如何创建数组并将其转换为正确格式的示例)。
如果要比较2个数组,它们将以分号分隔,但最后一个值后面将没有一个。如果将分号附加到数组的字符串形式(即a; b; c变为a; b; c;),则可以使用“ x;”进行匹配 无论处于什么位置:
bool found = false;
string someString = "a-b-c";
string[] arrString = someString.Split('-');
string myStringArray = arrString.ToString() + ";";
foreach (string s in otherArray)
{
if (myStringArray.IndexOf(s + ";") != -1) {
found = true;
break;
}
}
if (found == true) {
// ....
}
string [] lines = {"text1", "text2", "etc"};
bool bFound = lines.Any(x => x == "Your string to be searched");
如果搜索到的字符串与数组“ lines”的任何元素匹配,则bFound设置为true。
如果stringArray
包含大量不同长度的字符串,请考虑使用Trie来存储和搜索字符串数组。
public static class Extensions
{
public static bool ContainsAny(this string stringToCheck, IEnumerable<string> stringArray)
{
Trie trie = new Trie(stringArray);
for (int i = 0; i < stringToCheck.Length; ++i)
{
if (trie.MatchesPrefix(stringToCheck.Substring(i)))
{
return true;
}
}
return false;
}
}
这是Trie
该类的实现
public class Trie
{
public Trie(IEnumerable<string> words)
{
Root = new Node { Letter = '\0' };
foreach (string word in words)
{
this.Insert(word);
}
}
public bool MatchesPrefix(string sentence)
{
if (sentence == null)
{
return false;
}
Node current = Root;
foreach (char letter in sentence)
{
if (current.Links.ContainsKey(letter))
{
current = current.Links[letter];
if (current.IsWord)
{
return true;
}
}
else
{
return false;
}
}
return false;
}
private void Insert(string word)
{
if (word == null)
{
throw new ArgumentNullException();
}
Node current = Root;
foreach (char letter in word)
{
if (current.Links.ContainsKey(letter))
{
current = current.Links[letter];
}
else
{
Node newNode = new Node { Letter = letter };
current.Links.Add(letter, newNode);
current = newNode;
}
}
current.IsWord = true;
}
private class Node
{
public char Letter;
public SortedList<char, Node> Links = new SortedList<char, Node>();
public bool IsWord;
}
private Node Root;
}
如果输入的所有字符串stringArray
都具有相同的长度,则最好使用a HashSet
而不是aTrie
public static bool ContainsAny(this string stringToCheck, IEnumerable<string> stringArray)
{
int stringLength = stringArray.First().Length;
HashSet<string> stringSet = new HashSet<string>(stringArray);
for (int i = 0; i < stringToCheck.Length - stringLength; ++i)
{
if (stringSet.Contains(stringToCheck.Substring(i, stringLength)))
{
return true;
}
}
return false;
}
int result = Array.BinarySearch(list.ToArray(), typedString, StringComparer.OrdinalIgnoreCase);
试试这个,不需要循环。
string stringToCheck = "text1";
List<string> stringList = new List<string>() { "text1", "someothertext", "etc.." };
if (stringList.Exists(o => stringToCheck.Contains(o)))
{
}
就我而言,上述答案无效。我正在检查数组中的字符串,并将其分配给布尔值。我修改了@Anton Gogolev的答案,并删除了Any()
方法,并将其stringToCheck
放入Contains()
方法内部。
bool = stringArray.Contains(stringToCheck);
演示了三个选项。我更喜欢第三种方法。
class Program {
static void Main(string[] args) {
string req = "PUT";
if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
Console.WriteLine("one.1.A"); // IS TRUE
}
req = "XPUT";
if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
Console.WriteLine("one.1.B"); // IS TRUE
}
req = "PUTX";
if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
Console.WriteLine("one.1.C"); // IS TRUE
}
req = "UT";
if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
Console.WriteLine("one.1.D"); // false
}
req = "PU";
if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
Console.WriteLine("one.1.E"); // false
}
req = "POST";
if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
Console.WriteLine("two.1.A"); // IS TRUE
}
req = "ASD";
if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
Console.WriteLine("three.1.A"); // false
}
Console.WriteLine("-----");
req = "PUT";
if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0) {
Console.WriteLine("one.2.A"); // IS TRUE
}
req = "XPUT";
if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0) {
Console.WriteLine("one.2.B"); // false
}
req = "PUTX";
if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0) {
Console.WriteLine("one.2.C"); // false
}
req = "UT";
if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0) {
Console.WriteLine("one.2.D"); // false
}
req = "PU";
if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0) {
Console.WriteLine("one.2.E"); // false
}
req = "POST";
if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0) {
Console.WriteLine("two.2.A"); // IS TRUE
}
req = "ASD";
if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0) {
Console.WriteLine("three.2.A"); // false
}
Console.WriteLine("-----");
req = "PUT";
if ((new string[] {"PUT", "POST"}.Contains(req))) {
Console.WriteLine("one.3.A"); // IS TRUE
}
req = "XPUT";
if ((new string[] {"PUT", "POST"}.Contains(req))) {
Console.WriteLine("one.3.B"); // false
}
req = "PUTX";
if ((new string[] {"PUT", "POST"}.Contains(req))) {
Console.WriteLine("one.3.C"); // false
}
req = "UT";
if ((new string[] {"PUT", "POST"}.Contains(req))) {
Console.WriteLine("one.3.D"); // false
}
req = "PU";
if ((new string[] {"PUT", "POST"}.Contains(req))) {
Console.WriteLine("one.3.E"); // false
}
req = "POST";
if ((new string[] {"PUT", "POST"}.Contains(req))) {
Console.WriteLine("two.3.A"); // IS TRUE
}
req = "ASD";
if ((new string[] {"PUT", "POST"}.Contains(req))) {
Console.WriteLine("three.3.A"); // false
}
Console.ReadKey();
}
}