2 回答
TA贡献1815条经验 获得超10个赞
试试这个
import java.util.Arrays;
public class Reverse {
public static void main(String... args) {
getReversed("Tom Cat");
}
public static void getReversed(String str) {
char[] arr = str.toCharArray();
int len = 0;
for (char ch : arr) {
if (ch == ' ') {
len++;
}
}
String[] res = new String[len + 1];
int start = 0;
int idx = len;
while (idx > -1) {
StringBuilder builder = new StringBuilder();
for (int i = start; i < arr.length; i++) {
if (arr[i] != ' ') {
builder.append(arr[i]);
if (i == arr.length - 1) {
res[idx--] = builder.toString();
}
} else {
res[idx--] = builder.toString();
builder.setLength(0);
start = i;
}
}
}
System.out.println(Arrays.toString(res));
}
}
更新了优化代码
public static void main(String... args) {
String str = "Cat Tom";
char[] charArr = str.toCharArray();
int len = charArr.length;
ArrayList<String> list = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < len; i++) {
char ch = charArr[i];
if (ch == ' ') {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
} else if (i == len - 1) {
list.add(stringBuilder.append(ch).toString());
} else {
stringBuilder.append(ch);
}
}
Collections.reverse(list);
System.out.println(list);
}
输出
[Cat, Tom]
添加回答
举报