How to sort a string in c#.


I have a string and if you want to sort it in ascending order within it. For example I have a string “dabecfhg” and want to arrange this string as a sorted one like “abcdefg”. Here I don’t want to use any inbuilt function provided by C#.net.

Please find the Easy steps to do this task below.

1)declare the data types val as char, flag as bool.

2) Read the string from console.

3) Convert the string as string array.

4) Write a for loop starts from 0 to string array length.

5) Write a sub loop starts from 0 to string array length -1.

6) Check the condition strToChar[j] > strToChar[j + 1].

7)

val = strToChar[j];

strToChar[j] = strToChar[j + 1];

strToChar[j + 1] = val;

flag = true;

8) Now we are having the result in strToChar.




using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace ConsoleApplication3

{

class Program

{

static void Main(string[] args)

{

char val;

bool flag;

Console.WriteLine("Please enter a string to sort");

string myStr = Console.ReadLine();

char[] strToChar = myStr.ToCharArray();

for (int i = 0; i < strToChar.Length; i++)

{

flag = false;

for (int j = 0; j < strToChar.Length - 1; j++)

{

if (strToChar[j] > strToChar[j + 1])

{

val = strToChar[j];

strToChar[j] = strToChar[j + 1];

strToChar[j + 1] = val;

flag = true;

}

}

if (!flag) break;

}



for (int i = 0; i < strToChar.Length; i++)

Console.Write(strToChar[i]);

Console.Read();

}

}

}







Regards,
Naveen


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: