Is there an opposite of IndexOf ()? Perhaps NotIndexOf ()?

If myStr should contain 0 and 1, how can I look for this string for anything that is not 0 or 1?

For example:

string myStr = "1001g101";

if (myStr.IndexOf(NOT "0") != -1 && myStr.IndexOf(NOT "1") != -1) {
    Console.Write("String contains something that isn't 0 or 1!");
}

My reason for this is to not want to do a full ASCII character map and check every character on all ASCII characters, this seems too inefficient. If I need to check each character and provide 0 or 1, this will work, but is there a better way?

I feel bad with Regex, but I suspect that I can confirm my answer.

+4
source share
4 answers

Or use LINQ:

if (myStr.Any(c => c != '0' && c != '1'))
    ....
+8
source

I would go with LINQ, as Michael Gunther already did with his answer, but I would make it a little harder to make it easier to write / read and faster:

var desiredCharacters = new HashSet<char>() { '0', '1' };
var input = "1011001010110";

if(input.Any(x => !desiredCharacters.Contains(x)))
{
    Console.WriteLine("Input string contains something that is not defined in desiredCharacters collection.");
}

, desiredCharacters - , ||.

desiredCharacters, ||, .

Edit

All:

if(!input.All(desiredCharacters.Contains))
{
    //(...)
}
+3

.

^[01]*$

:

Match match = Regex.Match(myStr , @"^[01]*$");

if (!match.Success)
    Console.Write("String contains something that isn't 0 or 1!");
+2

, - , - O (m log n) time, m - s n chars:

public static int NotIndexOf( this string s , string chars )
{
  char[] orderedChars = chars.ToCharArray() ;
  Array.Sort( orderedChars ) ;

  int index = -1 ;
  for ( int i = 0 ; index < 0 && i < s.Length ; ++i )
  {
    int p = Array.BinarySearch(orderedChars, s[i] ) ;
    if ( p < 0 )
    {
      index = i ;
    }
  }
  return index ;
}

With regex, you just need to build the desired class of negative characters. On the other hand, with the exception of constructing a negative character set, it is quite simple. Here, I created a set of characters using Unicode escape-code code ( \uXXXX) to not have to deal with characters that are special in the context of the character set ( ], ^, -and \just for starters).

public static int NotIndexOf( this string s , string chars )
{
  StringBuilder regexString = new StringBuilder(3+6*chars.Length) ;
  regexString.Append("[^") ;
  foreach ( char c in chars.Distinct() )
  {
    regexString.AppendFormat( @"\u{0:X4}" , (ushort)c ) ;
  }
  regexString.Append("]") ;

  Regex rxCharSet = new Regex( regexString , Regex ) ;
  Match m         = rxCharSet.Match(s) ;

  return m.Success ? m.Index : -1 ;
}
0
source

All Articles