手動清理字符串往往在任何時間變得複雜。這通常是更好的(如果可能)代碼什麼你想要做的,而不是如何你想做的。
String input = "Hello my name is jason! Nice to meet you. What's your name?";
// this is *what* you want to do, part 1:
// split the input at each ' ', '.', '?' and '!', keep delimiter tokens
StringTokenizer st = new StringTokenizer(input, " .?!", true);
StringBuilder sb = new StringBuilder();
while(st.hasMoreTokens()) {
String token = st.nextToken();
// *what* you want to do, part 2:
// add each token to the start of the string
sb.insert(0, token);
}
String backwards = sb.toString();
System.out.print(input + "\n");
System.out.print(backwards);
輸出:
Hello my name is jason! Nice to meet you. What's your name?
?name your What's .you meet to Nice !jason is name my Hello
這將是一個更容易理解的是一段代碼,或者你的未來的自己的工作旁邊的人。
這假設你想要移動每個標點符號。如果你只想要一個輸入字符串的結尾,你必須切掉它的輸入,執行重新排序,並最終將其放置在字符串的開頭:
String punctuation = "";
String input = "Hello my name is jason! Nice to meet you. What's your name?";
System.out.print(input + "\n");
if(input.substring(input.length() -1).matches("[.!?]")) {
punctuation = input.substring(input.length() -1);
input = input.substring(0, input.length() -1);
}
StringTokenizer st = new StringTokenizer(input, " ", true);
StringBuilder sb = new StringBuilder();
while(st.hasMoreTokens()) {
sb.insert(0, st.nextToken());
}
sb.insert(0, punctuation);
System.out.print(sb);
輸出:
Hello my name is jason! Nice to meet you. What's your name?
?name your What's you. meet to Nice jason! is name my Hello
你的反向定義怎麼可能? '!'不是一個單獨的詞來獲得你想要的。它可以完成,但你的反向字符串順序思維是錯誤的。 – SkrewEverything
在每個單詞上,檢查它是否「結束」某個不是字母的東西。如果是這樣,將其移動到單詞的開頭。瞧。 –