C# Sharp Exercises: Compare the current string instance with another string
C# Sharp String: Exercise-33 with Solution
Write a C# Sharp program to compare the current string instance with another string.
Sample Solution:-
C# Sharp Code:
using System;
public class Example33
{
public static void Main()
{
string str1 = "Goodbye";
string str2 = "Hello";
string str3 = "a small string";
string str4 = "goodbye";
// Compare a string to itself.
Console.WriteLine(CompareStrings(str1, str1));
Console.WriteLine(CompareStrings(str1, str2));
Console.WriteLine(CompareStrings(str1, str3));
// Compare a string to another string that varies only by case.
Console.WriteLine(CompareStrings(str1, str4));
Console.WriteLine(CompareStrings(str4, str1));
}
private static string CompareStrings( string str1, string str2 )
{
// Compare the values, using the CompareTo method on the first string.
int cmpVal = str1.CompareTo(str2);
if (cmpVal == 0) // The strings are the same.
return "The strings occur in the same position in the sort order.";
else if (cmpVal > 0)
return "The first string precedes the second in the sort order.";
else
return "The first string follows the second in the sort order.";
}
}
Sample Output:
The strings occur in the same position in the sort order. The first string follows the second in the sort order. The first string precedes the second in the sort order. The first string precedes the second in the sort order. The first string follows the second in the sort order.
Flowchart :
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to compare a given string with set of strings.
Next: Write a C# Sharp program to concatenate three objects, objects with a variable and 3-element object array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework