How to read only 20 characters from a string and compare with another string?

I am working on hashing. I use a phrase, and I can only use 20 characters of a phrase.

How can I read only 20 characters of a string?

How to compare strings if they are the same?

+7
source share
6 answers

To read 20 characters of a string, you can use the substring method. So

myString = myString.Substring(0,20); 

will return the first 20 characters. However, this will throw an exception if you have less than 20 characters. You can make a method like this to give you the first 20 or the whole line if it is shorter.

 string FirstTwenty( string input ){ return input.Length > 20 ? input.Substring(0,20) : input; } 

Then to compare them

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

In case of UpperCase use this function

  if (FirstTwenty(mystring1).Equals(FirstTwenty(myString2), StringComparison.InvariantCultureIgnoreCase)) { //first twenty chars are the same for these two strings } 
+9
source

this compares the first 20 characters of the string a and b

 if (String.Compare(a, 0, b, 0, 20) == 0) { // strings are equal } 

for culture-specific comparison rules, you can use this overload, which accepts String enumeration

:
 if (String.Compare(a, 0, b, 0, 20, StringComparison.CurrentCultureIgnoreCase) == 0) { // case insensitive equal } 
+11
source

Compare the line with the line:

 bool stringsAreEqual = str1 == str2; 

Read the first 20 characters from the string (very confident):

 string first20chars = string.IsNullOrEmpty(str) ? str : str.Length >= 20 ? str.Substring(0, 20) : str; 
+4
source

Substring in a C # string The class returns a new string, which is a substring of this string. The substring starts at the specified given index and increases to the specified length.

 str = "This is substring test"; retString = str.Substring(5, 7); // "is" 

In your case you should use

 str.substring(0,20); 

To compare two strings, you use String.Equals ()

 String a = "Hello"; String b = "World"; if(a.Equals(b, true)); 

To ignore the case of strings, you must use "true".

+4
source
 string input = "..."; string first20 = input.Substring(0, 20); bool eq = String.Equals(first20, anotherString, StringComparison.Ordinal); 

See String.Substring () , String.Equals () on MSDN.

+3
source

Use Linq!

 if(new string(yourString.Take(20).ToArray()) == otherString.Take(20)) .... 

EDIT As mentioned in the comments, to change IEnumerable back to string. Fixed

You can only do this for listings:

 if(yourString.Take(20).SequenceEqual(other.AsEnumerable()) .... 

If you just want to check the start of lines:

 if(yourString.Take(20).SequenceEqual(other.Take(20)) .... 
0
source

All Articles