Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C# Sharp Exercises: Compare two substrings that only differ in case

C# Sharp String: Exercise-22 with Solution

Write a C# Sharp program to compare two substrings that only differ in case. The first comparison ignores case and the second comparison considers case.

Sample Solution:-

C# Sharp Code:

using System;
class Example22
{
    public static void Main() {
//                 01234567
    String str1 = "COMPUTER";
    String str2 = "computer";
    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) ? "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) ? "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);
    }
}
  

Sample Output:

str1 = 'COMPUTER', str2 = 'computer'                                                                          
Ignore case:                                                                                                  
Substring 'MP' in 'COMPUTER' is equal to substring 'mp' in 'computer'.                                        
                                                                                                              
Honor case:                                                                                                   
Substring 'MP' in 'COMPUTER' is greater than substring 'mp' in 'computer'.

Flowchart :

Flowchart: Compare two substrings that only differ in case.

Contribute your code and comments through Disqus.

Previous: Write a C# Sharp program to compare (less than, greater than, equal to ) two substrings.
Next: Write a C# Sharp program to compare two substrings using different cultures and ignoring the case of the substrings.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.