0

我尝试拆分行中的单词并检查它们是否有句号,但出现错误:

falls.falls.falls.Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at Alpha.main(Alpha.java:10)     

代码:

import java.io.*;
import java.util.*;

public class Alpha
{
    public static void main(String[] args)
    {
        String phrase = "the moon falls. the flowers grew.";
        String beta = "";
        String[] array = phrase.split(" ");
        for (int i = 0; i < array.length; i++)
        {
            if (array[i].endsWith("."))
            {
                array[i + 1] = array[i + 1].substring(0, 1).toUpperCase() + array[i + 1].substring(1);

                beta = beta + array[i];
            }
            System.out.print(beta);
        }
    }
}

(另外我不认为我会这样称呼数组的另一个词,关于如何解决这个问题的任何建议?)

4

4 回答 4

1

您没有处理输入以 . 结尾的情况..此外,一般句子在下一个句子之后之前可能有一个空格。你也应该考虑到这一点。此外,您可能想看看这个版本indexOf需要一个fromIndex.

于 2012-11-18T04:13:44.697 回答
0

基于问题的代码正则表达式匹配一个句子

import java.util.regex.*;
public class TEST {
    public static void main(String[] args) {
        String subjectString = 
        "This is a sentence. " +
        "So is \"this\"! And is \"this?\" " +
        "This is 'stackoverflow.com!' " +
        "Hello World";
        String[] sentences = null;
        Pattern re = Pattern.compile(
            "# Match a sentence ending in punctuation or EOS.\n" +
            "[^.!?\\s]    # First char is non-punct, non-ws\n" +
            "[^.!?]*      # Greedily consume up to punctuation.\n" +
            "(?:          # Group for unrolling the loop.\n" +
            "  [.!?]      # (special) inner punctuation ok if\n" +
            "  (?!['\"]?\\s|$)  # not followed by ws or EOS.\n" +
            "  [^.!?]*    # Greedily consume up to punctuation.\n" +
            ")*           # Zero or more (special normal*)\n" +
            "[.!?]?       # Optional ending punctuation.\n" +
            "['\"]?       # Optional closing quote.\n" +
            "(?=\\s|$)", 
            Pattern.MULTILINE | Pattern.COMMENTS);
        Matcher reMatcher = re.matcher(subjectString);
        while (reMatcher.find()) {
            String sentence = reMatcher.group();
            sentence = sentence.substring(0,1).toUpperCase() + sentence.substring(1);
            System.out.println(sentence);
        } 
    }
}
于 2012-11-18T04:14:04.303 回答
0

考虑一下:

    String phrase = "the moon falls. the flowers grew.";
    char[] a = phrase.toCharArray();
    boolean f = true;
    for (int i = 0; i < a.length; i++) {
        if (f) {
            if (a[i] != ' ') {
                a[i] = Character.toUpperCase(a[i]);
                f = false;
            }
        } else if (a[i] == '.') {
            f = true;
        }
    }
    phrase = new String(a);
    System.out.println(phrase);
于 2012-11-18T04:31:50.020 回答
0

我建议在“。”上使用 split()。这样,您可以检查句号后面是否有字符,然后将其大写。

于 2012-11-18T04:11:58.323 回答