How to reverse each word in a string with Java

3 Answers

0 votes
class ReverseEachWordInAString_Java {
    static String reverseEachWordInAString(String s) {
        String[] arr = s.split(" ");
        
        for (int i = 0; i < arr.length; i++) {
            char[] charArray = arr[i].toCharArray();
            for (int j = 0, k = charArray.length - 1; j < k; j++, k--) {
                char temp = charArray[j];
                charArray[j] = charArray[k];
                charArray[k] = temp;
            }
            arr[i] = new String(charArray);
        }
        
        return String.join(" ", arr);
    }

    public static void main(String[] args) {
        String s = "java c++ rust python c#";
        
        s = reverseEachWordInAString(s);
        
        System.out.println(s);
    }
}

 
 
/*
run:
     
avaj ++c tsur nohtyp #c
      
*/

 



answered Aug 30, 2024 by avibootz
0 votes
class ReverseEachWordInAString_Java {
    static String reverseEachWordInAString(String s) {
        String words[] = s.split("\\s");  
        String reverseWords = "";  
        
        for (String w : words) {  
            StringBuilder sb = new StringBuilder(w);  
            sb.reverse();  
            reverseWords += sb.toString() + " ";  
        }  
        
        return reverseWords.trim();  
    }

    public static void main(String[] args) {
        String s = "java c++ rust python c#";
        
        s = reverseEachWordInAString(s);
        
        System.out.println(s);
    }
}

 
 
/*
run:
     
avaj ++c tsur nohtyp #c
      
*/

 



answered Aug 30, 2024 by avibootz
0 votes
class ReverseEachWordInAString_Java {
    static String reverseEachWordInAString(String s) {
        String words[] = s.split("\\s");  
        String reverseWords = "";  
        
        for (String w : words) {  
            reverseWords += new StringBuilder(w).reverse().toString() + " ";  
        }  
        
        return reverseWords.trim();  
    }

    public static void main(String[] args) {
        String s = "java c++ rust python c#";
        
        s = reverseEachWordInAString(s);
        
        System.out.println(s);
    }
}

 
 
/*
run:
     
avaj ++c tsur nohtyp #c
      
*/

 



answered Aug 30, 2024 by avibootz

Related questions

1 answer 76 views
1 answer 71 views
1 answer 80 views
...