将两个String.Compare子字符串合并为一个

时间:2017-01-29 17:40:38

标签: c# .net string

所以我正在检查所选字符串是否包含substring + anything + substring1,现在我这样做:

if(line.Contains("2-") && line.Contains(":"))
{
    //work
}

还有其他方式,如line.Contains("2-[somesign]:")或其他任何方式

3 个答案:

答案 0 :(得分:2)

如果订单无关紧要,那么多次调用Contains就可以了。否则,您可以创建这样的扩展方法:

public static class StringExtension
{
    public static bool ContainsInOrder(this string value, params string[] args)
    {
        if (string.IsNullOrEmpty(value) || args == null || args.Length == 0)
            return false;

        int previousIndex = -1;
        foreach (string arg in args)
        {
            if (arg == null) return false;

            int index = value.IndexOf(arg);
            if (index == -1 || index < previousIndex)
            {
                return false;
            }
            previousIndex = index;
        }
        return true;
    }
} 

并像这样使用它:

"hello, world".ContainsInOrder("hello", ",", "world"); // true
"hello, world".ContainsInOrder("hello", null, "world"); // false
"hello, world".ContainsInOrder("hello", ":", "world"); // false
"hello, world".ContainsInOrder("hello", "world"); // true

答案 1 :(得分:0)

正则表达式是一个很好的解决方案。

using System.Text.RegularExpressions;

if(Regex.IsMatch(@"2-.*:"))
{
    //work
}

这将匹配any_string1 + "2-" + any_string2 + ":" + any_string3

这解决了评论中提到的问题,其中使用contains无法区分"2-"":"的顺序。

答案 2 :(得分:0)

   class Program {
      static void Main(String[] args) {
         // By using extension methods
         if ( "Hello world".ContainsAll(StringComparison.CurrentCultureIgnoreCase, "Hello", "world") ) 
            Console.WriteLine("Found everything by using an extension method!");
         else 
            Console.WriteLine("I didn't");

         // By using a single method
         if ( ContainsAll("Hello world", StringComparison.CurrentCultureIgnoreCase, "Hello", "world") )
            Console.WriteLine("Found everything by using an ad hoc procedure!");
         else 
            Console.WriteLine("I didn't");

      }

      private static Boolean ContainsAll(String str, StringComparison comparisonType, params String[] values) {
         return values.All(s => s.Equals(s, comparisonType));
      }    
   }

   // Extension method for your convenience
   internal static class Extensiones {
      public static Boolean ContainsAll(this String str, StringComparison comparisonType, params String[] values) {
         return values.All(s => s.Equals(s, comparisonType));
      }
   }