gpt4 book ai didi

java - 如何在每个句子的末尾添加一个空格?

转载 作者:行者123 更新时间:2023-11-29 04:18:44 25 4
gpt4 key购买 nike

我在我的 Android 应用程序中处理了几个句子。在每个句子的结尾,我需要添加一个额外的空格。我在下面尝试过。

bodyText=body.replaceAll("\\.",". ");

这确实有效,直到我在句子之间找到。例如,如果有一个带有十进制数字的句子,那么上面的代码也会为该数字添加一个空格。检查下面的示例,我在其中应用了上面的代码,但它没有按预期工作。

Last year the overall pass percentage was 90. 95%.  It was 96. 21% in 2016. 

您可以看到小数位是如何用空格分隔的。

如何只在句末加一个空格?通常每个句子结尾都会包含一个句号。

最佳答案

你可以得到你自己的代码的结果,如下所示

public static String modifySentence(String input) {

StringBuilder sb = new StringBuilder(input);
// Counter which will increase with every insertion of char in StringBuilder
int insertCounter = 1;

int index = input.indexOf(".");

// If index is not of last digit of input, or not a digit or not a space.
// In all above cases we need to skip
while (index >= 0) {
if ((index + 1 < input.length())
&& (!Character.isDigit(input.charAt(index + 1)))
&& (!Character.isSpaceChar(input.charAt(index + 1)))) {

sb.insert(index + insertCounter, " ");
insertCounter++;
}

index = input.indexOf(".", index + 1);
}
return sb.toString();
}

输入就像

System.out.println(modifySentence("Last year the overall pass percentage was 90.95%.It was 96.21% in 2016."));
System.out.println(modifySentence("Last year the overall pass percentage was 90.95%.It was 96.21% in 2016. And this is extra . test string"));

输出是

Last year the overall pass percentage was 90.95%. It was 96.21% in 2016.
Last year the overall pass percentage was 90.95%. It was 96.21% in 2016. And this is extra . test string

作为wiktor-stribiżew评论,同样的结果可以使用 your_string.replaceAll("\\.([^\\d\\s])", ". $1"); 实现.或者你可以使用 your_string.replaceAll("\\.(?<!\\d\\.\\d)(\\S)", ". $1") , 它会处理这种情况,就像 数字在点之后开始 一样。

如果您对这些正则表达式有任何困惑,可以直接(通过在评论中提及他)询问 wiktor-stribiżew .这些正则表达式归功于他。

关于java - 如何在每个句子的末尾添加一个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50580568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com