Java 如果句子没有以句号结尾,我需要增加一个count变量
大家好,我正在尝试制作一个基本的词法分析器,为此我需要将字符串拆分为几个句子,如果我的句子以句号结尾,它就会被拆分,请记住,有时人们可能不会在段落末尾加句号,变量仍然需要增加 例如:Java 如果句子没有以句号结尾,我需要增加一个count变量,java,Java,大家好,我正在尝试制作一个基本的词法分析器,为此我需要将字符串拆分为几个句子,如果我的句子以句号结尾,它就会被拆分,请记住,有时人们可能不会在段落末尾加句号,变量仍然需要增加 例如: String paragraph="first sentence. second sentence."; 数到2 要不是 String paragration=“第一句话。第二句话” 我需要数到2 for (int start = 0; start < input.length(); start++) {
String paragraph="first sentence. second sentence.";
数到2
要不是
String paragration=“第一句话。第二句话”
我需要数到2
for (int start = 0; start < input.length(); start++) {
if (input.charAt(start) == 46 ) {
count = count + 1;
}
}
System.out.print(count+" ");
String[] sentences = input.split("\\.");
System.out.print(" ");
for (int start = 0; start < count; start++) {
sentence.add(sentences[start]);
// sentence.size();
System.out.print(sentences[start]+" ");
}
for(int start=0;start
您可以使用字符串类方法endsWith(“\”)检查场景是否以结尾。然后按如下方式正确使用拆分:
//Check input scentense ends with . then number of sentences are less
// than total length of the array
if(input != null && input.endsWith("\\.")) {
String[] sentences = input.split("\\.");
count = sentences.length-1;
}
//else the scentense is NOT ending with .
// then array length gives the correct count of scentenses
else if(input != null && !input.endsWith("\\.")) {
String[] sentences = input.split("\\.");
count = sentences.length;
}
对于这种情况,不应该使用正则表达式 JDK有一个类是有原因的 使用BreakIterator类可以分析四种边界: 字符、单词、句子和可能的换行符。什么时候 实例化BreakIterator时,可以调用相应的工厂 方法: getCharacterInstance getWordInstance getSentenceInstance getLineInstance BreakIterator的每个实例只能检测一个 边界类型。如果要同时定位字符和单词 例如,可以创建两个单独的实例 只需计算句号:
int count = input.replaceAll("[^.]|\\.$", "").length() + 1;
替换(有效地)删除所有非点或尾随点。如果将字符串段落=“first Session.second Session”按点拆分,则将得到两个字符串。因此,您可以返回split方法返回的字符串数组的长度。谢谢,这个问题已经通过一个简单的连接解决了。实际上,如果句子没有以fullstop@Vibhor它是增加的。请参见末尾的
+1
?如果我没有删除内容中的尾随点,它将被重复计算-这就是为什么它先被删除,然后在末尾添加一个1
。