user4833678
user4833678

Reputation:

Sorting characters alphabetically in a String

Could smb please explaing the process of sorting characters of String alphabetically? For example, if I have String "hello" the output should be "ehllo" but my code is doing it wrong.

public static void main(String[] args)
    {
        String result = "";
        Scanner kbd = new Scanner(System.in);
        String input = kbd.nextLine();

        for(int i = 1; i < input.length(); i++)
        {
            if(input.charAt(i-1) < input.charAt(i))
                result += input.charAt(i-1);
            //else 
            //  result += input.charAt(i);
        }
        System.out.println(result);
    }


}

Upvotes: 8

Views: 95976

Answers (9)

Praveen Patel
Praveen Patel

Reputation: 36

Using a TreeMap data structure can help achieve a sorted order for the characters in a string in O(n) time complexity.

    Map<Character, Integer> charMap = new TreeMap<>();

    // Count the frequency of each character
    for (char c : str.toCharArray()) {
        charMap.put(c, charMap.getOrDefault(c, 0) + 1);
    }

    StringBuilder sortedString = new StringBuilder();

    // Build the sorted string
    for (Character c : charMap.keySet()) {
        int frequency = charMap.get(c);
        for (int i = 0; i < frequency; i++) {
            sortedString.append(c);
        }
    }
    return sortedString.toString();

Upvotes: 0

fsalazar_sch
fsalazar_sch

Reputation: 455

Your for loop is starting at 1 and it should be starting at zero:

for(int i = 0; i < input.length(); i++){...}

Upvotes: 1

Tarun Jadhav
Tarun Jadhav

Reputation: 1

public class SortCharcterInString {

public static void main(String[] args) {
    String str = "Hello World";
    char[] arr;
    List<Character> L = new ArrayList<Character>();
    for (int i = 0; i < str.length(); i++) {
        arr = str.toLowerCase().toCharArray();
        L.add(arr[i]);

    }
    Collections.sort(L);
    str = L.toString();
    str = str.replaceAll("\\[", "").replaceAll("\\]", "")
            .replaceAll("[,]", "").replaceAll(" ", "");
    System.out.println(str);

}

Upvotes: -1

user3133925
user3133925

Reputation:

Most basic and brute force approach using the two for loop: It sort the string but with the cost of O(n^2) time complexity.

public void stringSort(String str){
        char[] token = str.toCharArray();
        for(int i = 0; i<token.length; i++){
            for(int j = i+1; j<token.length; j++){
                if(token[i] > token[j]){
                    char temp = token[i];
                    token[i] = token[j];
                    token[j] = temp;
                }
            }
        }
        System.out.print(Arrays.toString(token));
    }

Upvotes: 0

bpjoshi
bpjoshi

Reputation: 1141

You can sort a String in Java 8 using Stream as below:

String sortedString =
    Stream.of("hello".split(""))
    .sorted()
    .collect(Collectors.joining());

Upvotes: 16

user8383675
user8383675

Reputation:

You can do this using Arrays.sort, if you put the characters into an array first.

Character[] chars = new Character[str.length()];

for (int i = 0; i < chars.length; i++)
    chars[i] = str.charAt(i);

// sort the array
Arrays.sort(chars, new Comparator<Character>() {
    public int compare(Character c1, Character c2) {
        int cmp = Character.compare(
            Character.toLowerCase(c1.charValue()),
            Character.toLowerCase(c2.charValue())
        );
        if (cmp != 0) return cmp;
        return Character.compare(c1.charValue(), c2.charValue());
    }
});

Now build a string from it using StringBuilder.

Upvotes: 0

rashedcs
rashedcs

Reputation: 3725

Procedure :

  1. At first convert the string to char array

  2. Then sort the array of character

  3. Convert the character array to string

  4. Print the string


Code snippet:

 String input = "world";
 char[] arr = input.toCharArray();
 Arrays.sort(arr);
 String sorted = new String(arr);
 System.out.println(sorted);

Upvotes: 4

Razib
Razib

Reputation: 11163

You may do the following thing -

1. Convert your String to char[] array.
2. Using Arrays.sort() sort your char array

Code snippet:

String input = "hello";
char[] charArray = input.toCharArray();
Arrays.sort(charArray);
String sortedString = new String(charArray);
System.out.println(sortedString);  

Or if you want to sort the array using for loop (for learning purpose) you may use (But I think the first one is best option ) the following code snippet-

input="hello";
char[] charArray = input.toCharArray();
length = charArray.length();

for(int i=0;i<length;i++){
   for(int j=i+1;j<length;j++){
      if (charArray[j] < charArray[i]) {
          char temp = charArray[i];
          charArray[i]=arr[j];
          charArray[j]=temp;
      }
   }
}

Upvotes: 22

GreySage
GreySage

Reputation: 1180

Sorting as a task has a lower bound of O(n*logn), with n being the number of elements to sort. What this means is that if you are using a single loop with simple operations, it will not be guaranteed to sort correctly. A key element in sorting is deciding what you are sorting by. In this case its alphabetically, which, if you convert each character to a char, equates to sorting in ascending order, since a char is actually just a number that the machine maps to the character, with 'a' < 'b'. The only gotcha to look out for is mixed case, since 'z' < 'A'. To get around, this, you can use str.tolower(). I'd recommend you look up some basic sorting algorithms too.

Upvotes: 1

Related Questions