comparing characters in strings

  • Last Update :
  • Techknowledgy :

If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. We’re done.,Otherwise, if both strings’ first characters are the same, compare the second characters the same way.,Mathematically, that’s strange. The last result states that "null is greater than or equal to zero", so in one of the comparisons above it must be true, but they are both false.,If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.

alert(2 > 1); // true (correct)
alert(2 == 1); // false (wrong)
alert(2 != 1); // true (correct)
let result = 5 > 4; // assign the result of the comparison
alert(result); // true
alert('Z' > 'A'); // true
alert('Glow' > 'Glee'); // true
alert('Bee' > 'Be'); // true
alert('2' > 1); // true, string '2' becomes a number 2
alert('01' == 1); // true, string '01' becomes a number 1
alert(true == 1); // true
alert(false == 0); // true
let a = 0;
alert(Boolean(a)); // false

let b = "0";
alert(Boolean(b)); // true

alert(a == b); // true!

Suggestion : 2

The program steps through the string referred to by searchMe one character at a time. For each character, the program calls the regionMatches method to determine whether the substring beginning with the current character matches the string the program is looking for.,The following program, RegionMatchesDemo, uses the regionMatches method to search for a string within another string:,The boolean argument indicates whether case should be ignored; if true, case is ignored when comparing characters.,The String class has a number of methods for comparing strings and portions of strings. The following table lists these methods.

public class RegionMatchesDemo {
   public static void main(String[] args) {
      String searchMe = "Green Eggs and Ham";
      String findMe = "Eggs";
      int searchMeLength = searchMe.length();
      int findMeLength = findMe.length();
      boolean foundIt = false;
      for (int i = 0; i <= (searchMeLength - findMeLength); i++) {
         if (searchMe.regionMatches(i, findMe, 0, findMeLength)) {
            foundIt = true;
            System.out.println(searchMe.substring(i, i + findMeLength));
            break;
         }
      }
      if (!foundIt)
         System.out.println("No match found.");
   }
}

Suggestion : 3

Last Updated : 12 May, 2022

  • Syntax 1: Compares the string *this with the string str.
int string::compare(const string & str) const
   Returns:
   0: if both strings are equal.
A value < 0: if * this is shorter than str or,
first character that doesn 't match is smaller than str.
A value > 0: if * this is longer than str or,
first character that doesn 't match is greater

Output: 

Geeks is smaller than forGeeks
Geeks is equal to Geeks
  • Syntax 2: Compares at most, len characters of string *this, starting with index idx with the string str.
int string::compare(size_type idx, size_type len,
   const string & str) const
   Throws out_of_range
if index > size().
  • Syntax 4: Compares the characters of string *this with the characters of the C-string cstr. 
int string::compare(const char * cstr) const
  • Syntax 5: Compares at most, len characters of string *this, starting with index idx with all characters of the C-string cstr.
int string::compare(size_type idx, size_type len,
   const char * cstr) const

Suggestion : 4

I would write the method like :

public boolean isSame() {
      if (s != null && s.length() == 1 {
            return s.charAt(0) == c;
         }
         return false;
      }

Either use char comparison (assuming s will always be of length 1):

return c == s.charAt(0);

Or use String comparison:

return s.equals(new String(new char[] {
   c
}));

Suggestion : 5

The comparison terminates when an inequality is discovered or both strings have been compared. However, if the two strings compare equal to the end of one string, and the other string has characters remaining, the string with the remaining characters is considered greater.,The comparison terminates when an inequality is discovered or both strings have been compared. However, if the two strings compare equal to the end of one string, and the other string has characters remaining, the string with remaining characters is considered greater. The return value is the result of the last comparison performed.,The comparison terminates when an inequality is discovered or both substrings have been compared. However, if the two strings compare equal to the end of one string, and the other string has characters remaining, the string with the remaining characters is considered greater. The return value is the result of the last comparison performed.,The comparison terminates when an inequality is discovered or both substrings have been compared. However, if the two strings compare equal to the end of one string, and the other string has characters remaining, the string with remaining characters is considered greater. The return value is the result of the last comparison performed.

1._
public:
   static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, System::Globalization::CultureInfo ^ culture, System::Globalization::CompareOptions options);
public static int Compare(string ? strA, int indexA, string ? strB, int indexB, int length, System.Globalization.CultureInfo ? culture, System.Globalization.CompareOptions options);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, System.Globalization.CultureInfo? culture, System.Globalization.CompareOptions options);
public static int Compare(string strA, int indexA, string strB, int indexB, int length, System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options);
static member Compare : string * int * string * int * int * System.Globalization.CultureInfo * System.Globalization.CompareOptions -> int
Public Shared Function Compare(strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, culture As CultureInfo, options As CompareOptions) As Integer

The following example uses the Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) method to compare the last names of two people. It then lists them in alphabetical order.

string name1 = "Jack Smith";
string name2 = "John Doe";

// Get position of character after the space character.
int index1 = name1.IndexOf(" ");
index1 = index1 < 0 ? 0 : ++index1;

int index2 = name2.IndexOf(" ");
index2 = index2 < 0 ? 0 : ++index2;

int length = Math.Max(name1.Length, name2.Length);

Console.WriteLine("Sorted alphabetically by last name:");
if (String.Compare(name1, index1, name2, index2, length,
      new CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0)
   Console.WriteLine("{0}\n{1}", name1, name2);
else
   Console.WriteLine("{0}\n{1}", name2, name1);

// The example displays the following output:
//       Sorted alphabetically by last name:
//       John Doe
//       Jack Smith
1._
public:
   static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public:
 static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public static int Compare(string ? strA, int indexA, string ? strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo ? culture);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo? culture);
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo culture);
static member Compare : string * int * string * int * int * bool * System.Globalization.CultureInfo -> int
Public Shared Function Compare(strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, ignoreCase As Boolean, culture As CultureInfo) As Integer

The following example compares two substrings using different cultures and ignoring the case of the substrings. The choice of culture affects how the letter "I" is compared.

// Sample for String::Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
using namespace System;
using namespace System::Globalization;
int main() {

   //                0123456
   String ^ str1 = "MACHINE";
   String ^ str2 = "machine";
   String ^ str;
   int result;
   Console::WriteLine();
   Console::WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
   Console::WriteLine("Ignore case, Turkish culture:");
   result = String::Compare(str1, 4, str2, 4, 2, true, gcnew CultureInfo("tr-TR"));
   str = ((result < 0) ? "less than" : ((result > 0) ? (String ^ )
      "greater than" : "equal to"));
   Console::Write("Substring '{0}' in '{1}' is ", str1 - > Substring(4, 2), str1);
   Console::Write(" {0} ", str);
   Console::WriteLine("substring '{0}' in '{1}'.", str2 - > Substring(4, 2), str2);
   Console::WriteLine();
   Console::WriteLine("Ignore case, invariant culture:");
   result = String::Compare(str1, 4, str2, 4, 2, true, CultureInfo::InvariantCulture);
   str = ((result < 0) ? "less than" : ((result > 0) ? (String ^ )
      "greater than" : "equal to"));
   Console::Write("Substring '{0}' in '{1}' is ", str1 - > Substring(4, 2), str1);
   Console::Write(" {0} ", str);
   Console::WriteLine("substring '{0}' in '{1}'.", str2 - > Substring(4, 2), str2);
}

/*
This example produces the following results:

str1 = 'MACHINE', str2 = 'machine'
Ignore case, Turkish culture:
Substring 'IN' in 'MACHINE' is less than substring 'in' in 'machine'.

Ignore case, invariant culture:
Substring 'IN' in 'MACHINE' is equal to substring 'in' in 'machine'.
*/
1._
public:
   static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, StringComparison comparisonType);
public:
 static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, StringComparison comparisonType);
public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType);
public static int Compare (string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType);
public static int Compare(string ? strA, int indexA, string ? strB, int indexB, int length, StringComparison comparisonType);
static member Compare : string * int * string * int * int * StringComparison -> int
Public Shared Function Compare(strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, comparisonType As StringComparison) As Integer

The following example compares two substrings.

// Sample for String::Compare(String, Int32, String, Int32, Int32)
using namespace System;
int main() {

   //                0123456
   String ^ str1 = "machine";
   String ^ str2 = "device";
   String ^ str;
   int result;
   Console::WriteLine();
   Console::WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
   result = String::Compare(str1, 2, str2, 0, 2);
   str = ((result < 0) ? "less than" : ((result > 0) ? (String ^ )
      "greater than" : "equal to"));
   Console::Write("Substring '{0}' in ' {1}' is ", str1 - > Substring(2, 2), str1);
   Console::Write(" {0} ", str);
   Console::WriteLine("substring '{0}' in ' {1}'.", str2 - > Substring(0, 2), str2);
}

/*
This example produces the following results:

str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
1._
public:
   static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, bool ignoreCase);
public:
 static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length, bool ignoreCase);
public static int Compare(string ? strA, int indexA, string ? strB, int indexB, int length, bool ignoreCase);
public static int Compare (string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase);
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase);
static member Compare : string * int * string * int * int * bool -> int
Public Shared Function Compare(strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer, ignoreCase As Boolean) As Integer

The following example performs two comparisons of two substrings that only differ in case. The first comparison ignores case and the second comparison considers case.

// Sample for String::Compare(String, Int32, String, Int32, Int32, Boolean)
using namespace System;
int main() {

   //                0123456
   String ^ str1 = "MACHINE";
   String ^ str2 = "machine";
   String ^ str;
   int result;
   Console::WriteLine();
   Console::WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
   Console::WriteLine("Ignore case:");
   result = String::Compare(str1, 2, str2, 2, 2, true);
   str = ((result < 0) ? "less than" : ((result > 0) ? (String ^ )
      "greater than" : "equal to"));
   Console::Write("Substring '{0}' in '{1}' is ", str1 - > Substring(2, 2), str1);
   Console::Write(" {0} ", str);
   Console::WriteLine("substring '{0}' in '{1}'.", str2 - > Substring(2, 2), str2);
   Console::WriteLine();
   Console::WriteLine("Honor case:");
   result = String::Compare(str1, 2, str2, 2, 2, false);
   str = ((result < 0) ? "less than" : ((result > 0) ? (String ^ )
      "greater than" : "equal to"));
   Console::Write("Substring '{0}' in '{1}' is ", str1 - > Substring(2, 2), str1);
   Console::Write(" {0} ", str);
   Console::WriteLine("substring '{0}' in '{1}'.", str2 - > Substring(2, 2), str2);
}

/*
This example produces the following results:

str1 = 'MACHINE', str2 = 'machine'
Ignore case:
Substring 'CH' in 'MACHINE' is equal to substring 'ch' in 'machine'.

Honor case:
Substring 'CH' in 'MACHINE' is greater than substring 'ch' in 'machine'.
*/
1._
public:
   static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length);
public:
 static int Compare(System::String ^ strA, int indexA, System::String ^ strB, int indexB, int length);
public static int Compare(string strA, int indexA, string strB, int indexB, int length);
public static int Compare (string strA, int indexA, string strB, int indexB, int length);
public static int Compare(string ? strA, int indexA, string ? strB, int indexB, int length);
static member Compare : string * int * string * int * int -> int
Public Shared Function Compare(strA As String, indexA As Integer, strB As String, indexB As Integer, length As Integer) As Integer

The following example compares two substrings.

// Sample for String::Compare(String, Int32, String, Int32, Int32)
using namespace System;
int main() {

   //                0123456
   String ^ str1 = "machine";
   String ^ str2 = "device";
   String ^ str;
   int result;
   Console::WriteLine();
   Console::WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
   result = String::Compare(str1, 2, str2, 0, 2);
   str = ((result < 0) ? "less than" : ((result > 0) ? (String ^ )
      "greater than" : "equal to"));
   Console::Write("Substring '{0}' in ' {1}' is ", str1 - > Substring(2, 2), str1);
   Console::Write(" {0} ", str);
   Console::WriteLine("substring '{0}' in ' {1}'.", str2 - > Substring(0, 2), str2);
}

/*
This example produces the following results:

str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/
1._
public:
   static int Compare(System::String ^ strA, System::String ^ strB);
public:
 static int Compare(System::String ^ strA, System::String ^ strB);
public static int Compare(string strA, string strB);
public static int Compare (string strA, string strB);
public static int Compare(string ? strA, string ? strB);
static member Compare : string * string -> int
Public Shared Function Compare(strA As String, strB As String) As Integer

The following example calls the Compare(String, String) method to compare three sets of strings.

using namespace System;

void main() {
   // Create upper-case characters from their Unicode code units.
   String ^ stringUpper = "\x0041\x0042\x0043";

   // Create lower-case characters from their Unicode code units.
   String ^ stringLower = "\x0061\x0062\x0063";

   // Display the strings.
   Console::WriteLine("Comparing '{0}' and '{1}':",
      stringUpper, stringLower);

   // Compare the uppercased strings; the result is true.
   Console::WriteLine("The Strings are equal when capitalized? {0}",
      String::Compare(stringUpper - > ToUpper(), stringLower - > ToUpper()) == 0 ?
      "true" : "false");

   // The previous method call is equivalent to this Compare method, which ignores case.
   Console::WriteLine("The Strings are equal when case is ignored? {0}",
      String::Compare(stringUpper, stringLower, true) == 0 ?
      "true" : "false");
}
// The example displays the following output:
//       Comparing 'ABC' and 'abc':
//       The Strings are equal when capitalized? true
//       The Strings are equal when case is ignored? true