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: Sort a string array in ascending order

C# Sharp String: Exercise-11 with Solution

Write a program in C# Sharp to sort a string array in ascending order.

C# Sharp Exercises: Sort a string array in ascending order.

Sample Solution:-

C# Sharp Code:

using System;  
public class Exercise11  
{  
    public static void Main() 
{
  string str;
  char[] arr1;
  char ch;
  int i,j,l;
      Console.Write("\n\nSort a string array in ascending order :\n");
      Console.Write("--------------------------------------------\n");  
      Console.Write("Input the string : ");
      str = Console.ReadLine();	
      l=str.Length;
      arr1 = str.ToCharArray(0, l);

   for(i=1;i<l;i++)
    for(j=0;j<l-i;j++)
	
	if(arr1[j]>arr1[j+1])
	{
	  ch=arr1[j];
	  arr1[j] = arr1[j+1];
	  arr1[j+1]=ch;
	}
   Console.Write("After sorting the string appears like : \n");
    foreach (char c in arr1)
       { 
        ch=c;
         Console.Write("{0} ",ch);
       }
       Console.WriteLine("\n");
   }
}

Sample Output:

Sort a string array in ascending order :                                                                      
--------------------------------------------                                                                  
Input the string : w3resource                                                                                 
After sorting the string appears like :                                                                       
3 c e e o r r s u w 

Flowchart:

Flowchart: Sort a string array in ascending order.

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to find maximum occurring character in a string.
Next: Write a program in C# Sharp to read a string through the keyboard and sort it using bubble sort.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.