[英]How to split String in java with question marks, points and exclamation marks
如何使用分隔符作为问号、点和感叹号将其拆分为 String 数组。 然后在每个大写字符之前放一个空格。 之后使该字符小写。
String one = "ATrueRebelYouAre!EveryoneWasImpressed.You'llDoWellToContinueInTheSameSpirit?";
要使用多个分隔符进行拆分,您可以使用正则表达式 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?
使用零宽度断言。 其中 ?= 是正向预测,而 ?<= 是负向预测。 我们可以在流中使用它,如下所示:
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?]
做到了!
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() + " ");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.