C# 是否有IndexOf()的对立面?可能是NotIndexOf()?
如果myStr应该包含0和1,那么如何在这个字符串中搜索不是0或1的内容 例如:C# 是否有IndexOf()的对立面?可能是NotIndexOf()?,c#,C#,如果myStr应该包含0和1,那么如何在这个字符串中搜索不是0或1的内容 例如: 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!"); } 我这样做的原因是不想做一个完整的ASCII字符映射,让它对照所有ASC
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!");
}
我这样做的原因是不想做一个完整的ASCII字符映射,让它对照所有ASCII字符检查每个字符,这似乎效率太低了。如果我必须检查每个字符,并确保0或1,这将起作用,但有更好的方法吗
我对正则表达式不太在行,但我怀疑这可能与我的答案相符。使用正则表达式。下面的正则表达式模式应该可以做到这一点
^[01]*$
示例代码为:
Match match = Regex.Match(myStr , @"^[01]*$");
if (!match.Success)
Console.Write("String contains something that isn't 0 or 1!");
或者使用LINQ:
if (myStr.Any(c => c != '0' && c != '1'))
....
我会选择LINQ,就像Michael Gunter在回答问题时所做的那样,但我会让它更复杂一些,让它更容易写/读和更快:
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.");
}
您可以使用类似这样的迭代,在O(m logn)时间内运行,其中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 ;
}
我不建议这样做,它可能太慢了。如果你想把LINQ和regex进行比较,没有全面的规则。测试并查看。您可以使用foreach(str中的var c)进行尝试。。。。这会很快,因为C#确实以一种特殊的方式优化了迭代器。如果使用正则表达式,它需要类似于
^[01]*$
。如果没有^
和$
,它将匹配诸如“g01”或“10foo”之类的内容。消息应该说:字符串中根本没有0
和1
,无法匹配当前的正则表达式。要得到OP想要的东西,请使用@“^[01]*$”
@MarcinJuraszek-谢谢!固定的
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 ;
}
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 ;
}