我尝试拆分行中的单词并检查它们是否有句号,但是我收到了错误:
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);
}
}
}
(另外我不认为我会怎么称呼数组中的另一个词,关于如何解决这个问题的任何建议?)
答案 0 :(得分:1)
您没有处理输入以.
结尾的情况。此外,一般句子在下一句之后.
之后可能有一个空格。你也应该考虑这一点。此外,您可能希望查看此版本的indexOf
,其中包含fromIndex
。
答案 1 :(得分:0)
我建议在“。”上使用split()。这样,您就可以检查句点后面是否有字符,然后将其大写。
答案 2 :(得分:0)
基于问题Regular expression match a sentence
的代码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);
}
}
}
答案 3 :(得分: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);