How to sort the words in a string in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static String sortTheWordsInAString(String s) {
        List<String> arr = new ArrayList<>();

        String[] tokens = s.split(" ");
        Collections.addAll(arr, tokens);

        Collections.sort(arr);

        StringBuilder sb = new StringBuilder();
        for (String str : arr) {
            sb.append(str).append(" ");
        }

        if (sb.length() > 0) {
            sb.setLength(sb.length() - 1); // Remove the last space
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        String s = "php c java c++ python c#";

        s = sortTheWordsInAString(s);

        System.out.println(s);
    }
}

 
 
/*
run:
    
c c# c++ java php python
  
*/

 



answered Jul 19, 2024 by avibootz
...