我想使用C#来检查字符串值是否包含字符串数组中的单词。例如,
string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext", etc... };
if(stringToCheck.contains stringArray) //one of the items?
{
}
如何检查'stringToCheck'的字符串值是否包含数组中的单词?
答案 0 :(得分:750)
以下是:
if(stringArray.Any(stringToCheck.Contains))
/* or a bit longer: (stringArray.Any(s => stringToCheck.Contains(s))) */
检查stringToCheck
是否包含stringArray
中的任何一个子字符串。如果您想确保它包含所有子字符串,请将Any
更改为All
:
if(stringArray.All(stringToCheck.Contains))
答案 1 :(得分:123)
这是你如何做到的:
string stringToCheck = "text1";
string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };
foreach (string x in stringArray)
{
if (stringToCheck.Contains(x))
{
// Process...
}
}
更新:可能您正在寻找更好的解决方案..请参阅@Anton Gogolev下面的答案,该答案使用了LINQ。
答案 2 :(得分:36)
无需使用LINQ
if (Array.IndexOf(array, Value) >= 0)
{
//Your stuff goes here
}
答案 3 :(得分:30)
只需使用linq方法:
stringArray.Contains(stringToCheck)
答案 4 :(得分:8)
最简单和样本方式。
bool bol=Array.Exists(stringarray,E => E == stringtocheck);
答案 5 :(得分:6)
string strName = "vernie";
string[] strNamesArray = { "roger", "vernie", "joel" };
if (strNamesArray.Any(x => x == strName))
{
// do some action here if true...
}
答案 6 :(得分:5)
或许这样的事情:
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!");
}
答案 7 :(得分:3)
使用Linq和方法组将是最快捷,更紧凑的方式。
var arrayA = new[] {"element1", "element2"};
var arrayB = new[] {"element2", "element3"};
if (arrayB.Any(arrayA.Contains)) return true;
答案 8 :(得分:2)
您可以定义自己的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();
}
}
答案 9 :(得分:1)
您也可以尝试此解决方案。
string[] nonSupportedExt = { ".3gp", ".avi", ".opus", ".wma", ".wav", ".m4a", ".ac3", ".aac", ".aiff" };
bool valid = Array.Exists(nonSupportedExt,E => E == ".Aac".ToLower());
答案 10 :(得分:1)
stringArray.ToList().Contains(stringToCheck)
答案 11 :(得分:1)
我会使用Linq,但仍可通过以下方式完成:
new[] {"text1", "text2", "etc"}.Contains(ItemToFind);
答案 12 :(得分:1)
我在控制台应用程序中使用以下内容来检查参数
var sendmail = args.Any( o => o.ToLower() == "/sendmail=true");
答案 13 :(得分:1)
尝试:
String[] val = { "helloword1", "orange", "grape", "pear" };
String sep = "";
string stringToCheck = "word1";
bool match = String.Join(sep,val).Contains(stringToCheck);
bool anothermatch = val.Any(s => s.Contains(stringToCheck));
答案 14 :(得分:1)
你也可以做同样的事情,就像Anton Gogolev建议检查stringArray1
中的任何项目是否匹配stringArray2
中的任何项目:< / p>
if(stringArray1.Any(stringArray2.Contains))
同样,stringArray1中的所有项与stringArray2中的所有项相匹配:
if(stringArray1.All(stringArray2.Contains))
答案 15 :(得分:0)
大多数解决方案都是正确的,但是如果您需要不区分大小写的检查值
using System.Linq;
...
string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext"};
if(stringArray.Any(a=> String.Equals(a, stringToCheck, StringComparison.InvariantCultureIgnoreCase)) )
{
//contains
}
if (stringArray.Any(w=> w.IndexOf(stringToCheck, StringComparison.InvariantCultureIgnoreCase)>=0))
{
//contains
}
答案 16 :(得分:0)
if(Array.Find(stringArray, stringToCheck.Contains) != null)
{
}
if(Array.FindIndex(stringArray, stringToCheck.Contains) != -1)
{
}
答案 17 :(得分:0)
对于我来说,上述答案无效。我正在检查数组中的字符串,并将其分配给布尔值。我修改了@Anton Gogolev的答案,并删除了Any()
方法,并将stringToCheck
放在了Contains()
方法中。
bool = stringArray.Contains(stringToCheck);
答案 18 :(得分:0)
要完成上述答案,请 IgnoreCase 使用:
stringArray.Any(s => stringToCheck.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) > -1)
答案 19 :(得分:0)
试试这个,这里的示例:检查字段是否包含数组中的任何单词。检查字段(someField)是否包含数组中的任何单词。
String[] val = { "helloword1", "orange", "grape", "pear" };
Expression<Func<Item, bool>> someFieldFilter = i => true;
someFieldFilter = i => val.Any(s => i.someField.Contains(s));
答案 20 :(得分:0)
试试这个,不需要循环..
string stringToCheck = "text1";
List<string> stringList = new List<string>() { "text1", "someothertext", "etc.." };
if (stringList.Exists(o => stringToCheck.Contains(o)))
{
}
答案 21 :(得分:0)
string [] lines = {"text1", "text2", "etc"};
bool bFound = lines.Any(x => x == "Your string to be searched");
如果搜索的字符串与数组&#39;行的任何元素匹配,则bFound设置为true。
答案 22 :(得分:0)
[5L, 6L]
答案 23 :(得分:0)
public bool ContainAnyOf(string word, string[] array)
{
for (int i = 0; i < array.Length; i++)
{
if (word.Contains(array[i]))
{
return true;
}
}
return false;
}
答案 24 :(得分:0)
简单的解决方案,不需要linq任何
String.Join(&#34;,&#34;,array).Contains(Value +&#34;,&#34;);
答案 25 :(得分:0)
如果<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="1">
<div class="2">
<div class="3">
<p class="4">Hello World</p>
</div>
</div>
</div>
包含大量不同长度的字符串,请考虑使用Trie来存储和搜索字符串数组。
stringArray
以下是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
代替HashSet
Trie
答案 26 :(得分:0)
我使用了与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) {
// ....
}
答案 27 :(得分:0)
试试这个
string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };
var t = lines.ToList().Find(c => c.Contains(stringToCheck));
它将返回您正在查找的文本的第一个出处的行。
答案 28 :(得分:-1)
我使用以下代码检查字符串是否包含字符串数组中的任何项:
foreach (string s in stringArray)
{
if (s != "")
{
if (stringToCheck.Contains(s))
{
Text = "matched";
}
}
}
答案 29 :(得分:-1)
展示了三个选项。我更愿意发现第三个是最简洁的。
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();
}
}