1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public class ReverseWordsInAString { public String reverseWords(String s) { if (s == null) { return s; } String[] splits = s.split(" "); StringBuilder sb = new StringBuilder(); for (int i = splits.length - 1; i >= 0; i--) { String str = splits[i].trim(); if (!str.isEmpty() && !str.equals(" ")) { sb.append(str).append(' '); } } return sb.toString().trim(); } }
|