简体   繁体   中英

Merging two String.Compare substrings into one

So i am checking if selected string contains substring + anything + substring1 , and now i am doing it like this:

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

Is there any other way like line.Contains("2-[somesign]:") or anyting like that

If the order does not matter, then calling Contains multiple times is fine. Else, you can create an extension method like this:

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;
    }
} 

And use it like this:

"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

A regular expression is a good solution.

using System.Text.RegularExpressions;

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

This will match any_string1 + "2-" + any_string2 + ":" + any_string3 .

This addresses the concern mentioned in the comments where using contains will not differentiate the order of the "2-" and the ":" .

   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));
      }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM