Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,161 questions

56,039 answers

573 users

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
...