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 a given string with set of strings

C# Sharp String: Exercise-32 with Solution

Write a C# Sharp program to compare a given string with set of strings.

Sample Solution:-

C# Sharp Code:

using System;

public class TestClass
{}

public class Example32 
{
   public static void Main()
   {
      var test = new TestClass();
      Object[] objectsToCompare = { test, test.ToString(), 123,
                                    123.ToString(), "some text",
                                    "Some Text" };
      string s = "some text";
      foreach (var objectToCompare in objectsToCompare) {
         try {
            int i = s.CompareTo(objectToCompare);
            Console.WriteLine("Comparing '{0}' with '{1}': {2}",
                              s, objectToCompare, i);
         }
         catch (ArgumentException) {
            Console.WriteLine("Bad argument: {0} (type {1})",
                              objectToCompare,
                              objectToCompare.GetType().Name);
         }
      }
   }
}

Sample Output:

Bad argument: TestClass (type TestClass)                                                                      
Comparing 'some text' with 'TestClass': -1                                                                    
                                                                                                              
                                                                                                              
Bad argument: 123 (type Int32)                                                                                
Comparing 'some text' with '123': 1                                                                           
                                                                                                              
Comparing 'some text' with 'some text': 0                                                                     
                                                                                                              
Comparing 'some text' with 'Some Text': -1  

Flowchart :

Flowchart: C# Sharp Exercises - Compare a given string with set of strings.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# Sharp program to perform and ordinal comparison of two strings that only differ in case.
Next: Write a C# Sharp program to compare the current string instance with another string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.