w3resource
C# Sharp Programming Exercises

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?



New Content: Composer: Dependency manager for PHP, R Programming