C Sharp > String.Contains - метод (String)
29.11.2016 16:01:53
Наиболее часто встречающиеся слова в статье:
[StringComparison] [Console] [WriteLine] [сравнение] [Contains] [подстроки] [регистра] [Следующий] [substring] [значение]
Статья:
Возвращает значение, указывающее, содержит ли указанная строка значение подстроки переданной в качестве параметра.
using System; public static class StringExtensions { public static bool Contains(this String str, String substring, StringComparison comp) { if (substring == null) throw new ArgumentNullException("substring", "substring cannot be null."); else if (! Enum.IsDefined(typeof(StringComparison), comp)) throw new ArgumentException("comp is not a member of StringComparison", "comp"); return str.IndexOf(substring, comp) >= 0; } }
Следующий пример вызывает Contains метод расширения, чтобы определить, находится ли подстроки в строке, при использовании порядкового сравнения и порядковое сравнение без учета регистра.
using System; public class Example { public static void Main() { String s = "This is a string."; String sub1 = "this"; Console.WriteLine("Does ''{0}'' contain ''{1}''?", s, sub1); StringComparison comp = StringComparison.Ordinal; Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp)); comp = StringComparison.OrdinalIgnoreCase; Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp)); } } // The example displays the following output: // Does ''This is a string.'' contain ''this''? // Ordinal: False // OrdinalIgnoreCase: True
using System; class Example { public static void Main() { string s1 = "The quick brown fox jumps over the lazy dog"; string s2 = "fox"; bool b = s1.Contains(s2); Console.WriteLine("''{0}'' is in the string ''{1}'': {2}", s2, s1, b); if (b) { int index = s1.IndexOf(s2); if (index >= 0) Console.WriteLine("''{0} begins at character position {1}", s2, index + 1); } } } // This example display the following output: // ''fox'' is in the string ''The quick brown fox jumps over the lazy dog'': True // ''fox begins at character position 17