C#: 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;
// Define the Example22 class
class Example22
{
// Main method - entry point of the program
public static void Main()
{
// Define and initialize string variables
String str1 = "COMPUTER"; // String 1
String str2 = "computer"; // String 2
String str; // String to store comparison result
int result; // Result of the comparison
// Display initial strings
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
// Ignore case while comparing substrings
Console.WriteLine("Ignore case:");
// Compare a substring of str1 starting at index 2 with a substring of str2 starting at index 2, each with a length of 2, ignoring case
result = String.Compare(str1, 2, str2, 2, 2, true);
// Determine the relationship between the compared substrings
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
// Display the comparison result
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();
// Honor case while comparing substrings
Console.WriteLine("Honor case:");
// Compare a substring of str1 starting at index 2 with a substring of str2 starting at index 2, each with a length of 2, honoring case
result = String.Compare(str1, 2, str2, 2, 2, false);
// Determine the relationship between the compared substrings
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
// Display the comparison result
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 :
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/csharp-exercises/string/csharp-string-exercise-22.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics