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 string whether they are equal or not

C# Sharp String: Exercise-6 with Solution

Write a program in C# Sharp to compare two strings without using string library functions.

C# Sharp Exercises: Compare two strings whether they are equal or not

Sample Solution:-

C# Sharp Code:

using System;  
public class Exercise6
{  
    public static void Main() 
{
    string str1, str2;
    int flg=0;
	int i=0,l1,l2,yn=0;
	
      Console.Write("\n\nCompare two strings whether they are equal or not :\n");
      Console.Write("------------------------------------------------------\n"); 	
      Console.Write("Input the 1st string : ");
      str1 = Console.ReadLine();	   
	   
      Console.Write("Input the 2nd string : ");
      str2 = Console.ReadLine();	   

	  l1=str1.Length;
	  l2=str2.Length;
/*compare checking when they are equal in length*/	  
if(l1==l2)
  {
    for(i=0;i<l1;i++)
     {
        if(str1[i] != str2[i])
          {
            yn=1;
            i=l1;
           
          }
     }
  }
/*initialize the flage where they are equal, smaller and greater in length*/  
    if(l1 == l2)
        flg=0;
    else if(l1 > l2)
        flg=1;
    else if(l1 < l2)
        flg=-1;
/*display the message where the strings are same or smaller or greater*/  
    if(flg == 0)
    {
       if(yn==0)
       Console.Write("\nThe length of both strings are equal and \nalso, both strings are same.\n\n");
       else
            Console.Write("\nThe length of both strings are equal \nbut they are not same.\n\n");
    }
    else if(flg == -1)
    {
       Console.Write("\nThe length of the first string is smaller than second.\n\n");
    }
    else
    {
       Console.Write("\nThe length of the first string is greater than second.\n\n");
    }
	}
}

Sample Output:

Compare two strings whether they are equal or not :                     
------------------------------------------------------                 
Input the 1st string : This is the first string.                       
Input the 2nd string : This is the second string.                      
                                                                       
The length of the first string is smaller than second.

Flowchart:

Flowchart: Compare two string whether they are equal or not.

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to count the total number of words in a string.
Next: Write a program in C# Sharp to count a total number of alphabets, digits and special characters in a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.