如何从字符串中只读取20个字符并与其他字符串进行比较?

New*_*der 7 .net c# string-comparison

我正在研究哈希.我正在编写一个短语,我只能使用该短语的20个字符.

如何只读取字符串的20个字符?

如果它们相同,我如何比较字符串?

thu*_*eys 12

这比较了字符串a和字符串的前20个字符b

if (String.Compare(a, 0, b, 0, 20) == 0)
{
    // strings are equal
}
Run Code Online (Sandbox Code Playgroud)

对于特定于文化的比较规则,您可以使用此重载,它接受StringComparison枚举:

if (String.Compare(a, 0, b, 0, 20, StringComparison.CurrentCultureIgnoreCase) == 0)
{
    // case insensitive equal
}
Run Code Online (Sandbox Code Playgroud)

  • 如果内置功能+1,为什么要手动使用子字符串 (2认同)
  • +1也不知道这个重载,它实际上非常有用:) (2认同)

Øyv*_*hen 9

要读取20个字符串的字符,可以使用substring方法.所以

myString = myString.Substring(0,20);
Run Code Online (Sandbox Code Playgroud)

将返回前20个字符.但是,如果您的字符少于20个,则会抛出异常.您可以使用这样的方法为您提供前20个,或者如果它更短,则为所有字符串.

string FirstTwenty( string input ){
  return input.Length > 20 ? input.Substring(0,20) : input;
}
Run Code Online (Sandbox Code Playgroud)

然后比较它们

if(FirstTwenty(myString1).CompareTo(FirstTwenty(myString2)) == 0){
  //first twenty chars are the same for these two strings
}
Run Code Online (Sandbox Code Playgroud)

如果是UpperCase,则使用此功能

 if (FirstTwenty(mystring1).Equals(FirstTwenty(myString2), StringComparison.InvariantCultureIgnoreCase))
    {
        //first twenty chars are the same for these two strings
    }
Run Code Online (Sandbox Code Playgroud)

  • C#也有运算符重载,你应该只使用`==` (2认同)