Q. Write an algorithm and program to sort string of characters in dictionaly order.
Solution : Given a string contain lowercase character from a to z and our task is to sort them in dictionary order.
String :- A string is a sequence of characters terminated with a null character \0 .
For example: char lfc[] = "letsfindcourse";
Sort String Characters Algorithm
//Algorithm To Sort String Of Characters START Step 1 -> Take string as input str. Step 2 -> Store the count of each character in one array ARR, index 0 corresponding to a and so on. Step 3 -> Now repeat loop I till the end of array ARR Step 4 -> Repeat inner loop on the basis of value of ARR[I] Step 5 -> Print ('a' + I) Step 6 -> End Inner loop Step 7 -> End Loop STOP
Sort String Characters Program
//C Program To Sort String Of Characters. #include <stdio.h> int main() { char str[20]="letsfindcourse"; int len=sizeof(str); int charCount[26] = {0}; for (int i=0; i<len; i++) charCount[str[i]-'a']++; for (int i=0;i<26;i++) for (int j=0;j<charCount[i];j++) printf("%c",(char)('a'+i)); return 0; }
//C++ Program To Sort String Of Characters. #include <iostream> using namespace std; int main() { string str = "letsfindcourse"; int charCount[26] = {0}; for (int i=0; i<str.length(); i++) charCount[str[i]-'a']++; for (int i=0;i<26;i++) for (int j=0;j<charCount[i];j++) cout << (char)('a'+i); return 0; }
//Java Program To Sort String Of Characters. public class LFC { public static void main(String[] args) { String str="letsfindcourse"; int alphabet[] = new int[26]; for (char x : str.toCharArray()) { alphabet[x - 'a']++; } for (int i = 0; i < 26; i++) { for (int j = 0; j < alphabet[i]; j++) { System.out.print((char) (i + 'a')); } } } }
//Python Program To Sort String Of Characters. str1="letsfindcourse" charCount = [0 for i in range(26)] for i in range(0, len(str1), 1): charCount[ord(str1[i]) - ord('a')] += 1 for i in range(0, 26, 1): for j in range(0, charCount[i], 1): print(chr(ord('a') + i), end = "")
//C# Program To Sort String Of Characters. using System; class LFC { static void Main() { string str = "letsfindcourse"; char[] tempArray = str.ToCharArray(); Array.Sort(tempArray); Console.WriteLine(tempArray); } }
//PHP Program To Sort String Of Characters. <?php $str = 'letsfindcourse'; $strsplit = preg_split('//u', $str); sort($strsplit); echo implode('', $strsplit); ?>
//C Program To Sort String Of Characters. #include <stdio.h> int main() { char str[20]="letsfindcourse"; int len=sizeof(str); int charCount[26] = {0}; for (int i=0; i<len; i++) charCount[str[i]-'a']++; for (int i=0;i<26;i++) for (int j=0;j<charCount[i];j++) printf("%c",(char)('a'+i)); return 0; }
Output
cdeefilnorsstu
Recommended Programs
Program to find length of given string.Program to find smallest element in an array.