我制作了这个程序,它将翻转如下句子: 用户输入:你好,我饿了。冰箱在哪里。 系统输出:饿了,我是你好。冰箱在哪里。
但是最后一个词和“.”之间有空格。在倒装句中。我怎样才能删除?我怎样才能使第一个单词成为大写单词?
package etzale;
public class etzale {
public static void main(String[] args) {
StringBuilder outputString= new StringBuilder();
String satz;
System.out.print("Bitte geben Sie einen String ein: ");
String text="Hallo mir gehts gut. Wie gehts dir. mir gehts spitze.";
while(text.indexOf(".")>=0){
satz=text.substring(0, text.indexOf("."));
text=text.substring(text.indexOf(".")+1);
String []s= satz.split(" ");
for(int i=s.length-1; i>=0; i--){
outputString.append(s[i]);
if(s[0]==" ");
outputString.append(" ");
}
outputString.append(".");
outputString.append(" ");
}
System.out.print(outputString);
}
}
如何删除最后一个单词和“.”之间的空格?在每个句子中?
Actual Input: Mit gehts gut. Wie gehts dir. Mir gehts spitze.
Actual Output: gut gehts mir . dir gehts Wie . spitze gehts Mir .
最佳答案
我已经回答了另一个与您几乎类似的问题:Reverse all words, set "." and do the same for the next sentences ,我的解决方案涵盖了这种情况,也尝试一下:
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
final String userInput = "Hello i´m hungry. Where is the fridge.";
final String expectedResult = "Hungry i´m Hello. Fridge the is Where.";
String[] sentences = userInput.split("\\. ");
String reversedSentences = Stream.of(sentences)
.map(sentenceString -> new Sentence(sentenceString))
.map(Sentence::reverse)
.map(Sentence::firstLetterToUpperCase)
.map(Sentence::removeAllDots)
.map(Sentence::dotInTheEnd)
.map(Sentence::toString)
.collect(Collectors.joining(" "));
System.out.println(reversedSentences.equals(expectedResult)); //returns true
}
}
final class Sentence {
private final String sentence;
Sentence(String sentence) {
this.sentence = sentence;
}
Sentence reverse() {
String[] words = sentence.split(" ");
Collections.reverse(Arrays.asList(words));
return new Sentence(String.join(" ", words));
}
Sentence firstLetterToUpperCase() {
String firstLetter = sentence.substring(0, 1);
String anotherPart = sentence.substring(1);
return new Sentence(firstLetter.toUpperCase() + anotherPart);
}
Sentence dotInTheEnd() {
return new Sentence(sentence + ".");
}
Sentence removeAllDots() {
return new Sentence(sentence.replaceAll("\\.", ""));
}
public String toString() {
return sentence;
}
}
关于java - 删除空格和大写首字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47640003/