如何使用分隔符作为问号,点和感叹号将其拆分为String数组。然后在每个大写字符前加一个空格。之后将这些字符设为小写。
String one = "ATrueRebelYouAre!EveryoneWasImpressed.You'llDoWellToContinueInTheSameSpirit?";
答案 0 :(得分:0)
对于使用多个分隔符进行拆分,可以使用正则表达式OR运算符:
String[] tokens = one.split("\\?|\\.|\\!");
在每个大写字母之前放置一个空格:
String two = "";
for (int i = 0; i < tokens.length; i++) {
String phrase = tokens[i];
String outputString = "";
for (int k = 0; k < phrase.length(); k++) {
char c = phrase.charAt(k);
outputString += Character.isUpperCase(c) ? " " + c : c;
}
two += outputString + " ";
}
two = two.replaceAll("\\s+", " ");
这将打印以下内容:
A True Rebel You Are Everyone Was Impressed You'll Do Well To Continue In The Same Spirit
但你也可以这样做:
String two = "";
for (int k = 0; k < one.length(); k++) {
char c = one.charAt(k);
two += Character.isUpperCase(c) ? " " + c : c;
}
two = two.replaceAll("\\s+", " ");
System.out.println(two);
将打印出来:
A True Rebel You Are! Everyone Was Impressed. You'll Do Well To Continue In The Same Spirit?
答案 1 :(得分:0)
使用zero-width assertion。其中?=是正向,而<< =是负向。我们可以在流中使用它,如下所示:
List<String> collect = Arrays.stream(one.split("(?<=[?.!])"))
.map(sentence -> sentence.replaceAll("(?=[A-Z])", " ").trim() )
.collect(Collectors.toList());
结果如下:
[A True Rebel You Are!, Everyone Was Impressed., You'll Do Well To Continue In The Same Spirit?]
答案 2 :(得分:-1)
做到了!
String one = "ATrueRebelYouAre!EveryoneWasImpressed.You'llDoWellToContinueInTheSameSpirit?";
String oneWithSpaces = one.replace("!","! ").replace("?","? ").replace(".",". ");
String[] splitedWithDelimeters = oneWithSpaces.split(" ");
for (int j = 0; j < splitedWithDelimeters.length; j++) {
String[] str = splitedWithDelimeters[j].split("(?=[A-Z])");
for (int i = 0; i < str.length; i++) {
if (i == 0) {
System.out.print(str[i] + " ");
} else if (i > 0) {
System.out.print(str[i].toLowerCase() + " ");
}
}
}