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

时间:2018-05-29 09:13:28

标签: java android regex string

我在Android应用中处理了几句话。在每个句子的末尾,我需要添加一个额外的空白区域。我在下面试过。

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

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

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

您可以看到小数位用空格分隔的方式。

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

3 个答案:

答案 0 :(得分:3)

您可以获得自己代码的结果,如下所示

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提问。这些正则表达式归功于他。

答案 1 :(得分:0)

我不知道这是否正确但你可以在点(。)之后检查后者是否为大写(大写后者),然后你可以考虑这个法则的结尾并添加一个空格。如果您的语句后来从小写开始,则不能使用它。

但很难检查第一个字母是否为大写。

但你也可以用

来做
 String first = myString.substring(0,1);

myString应该在点(。)之后,它不应该以任何数字开头。

答案 2 :(得分:0)

如果您想为句号后面已经有空格的句子添加额外空格,可以执行以下操作:

String sentence = "Last year the overall pass percentage was 90.95%.  It was 96.21% in 2016.";
    sentence = sentence.replaceAll("\\. ",".  ");

但是如果您需要在句点之后为空格分隔的句子添加空格,请执行以下操作:

import java.util.regex.*; 
public class MyClass {
public static void main(String args[]) {
    String sentence = "Last year the overall pass percentage was 90.95%.It was 96.21% in 2016.example.";
    String[] sentenceArr=sentence.split("\\.");  
    String str = "";
    for(int i = 0; i < sentenceArr.length; i++) {

        if(Pattern.matches(".*\\d+",sentenceArr[i]) && Pattern.matches("\\d+.*",sentenceArr[i+1])){
            str=str+sentenceArr[i]+".";
        }
        else{
            str=str+sentenceArr[i]+". ";
        }

    }
    System.out.println(str);
}

}

输入:去年总体通过率为90。95%。2016年为96.21%。示例

产出:去年整体通过率为90.95%。 2016年为96.21%。例如。