手动清理字符串往往在任何时间变得复杂。这通常是更好的(如果可能)代码什么你想要做的,而不是如何你想做的。
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
在每个单词上,检查它是否“结束”某个不是字母的东西。如果是这样,将其移动到单词的开头。瞧。 –