2016-11-06 252 views
0

我试图从字符串中删除标点符号,但保留空格,因为我需要能够区分不同的单词。最终目标是找出字符串中每个单词的长度。删除标点符号java

我设置了一个for循环来检查单词的长度,直到它遇到空格为止,但这会将标点符号计为一个字母。我知道我必须更改if语句中的变量,以反映字符串中空格的iindexOf之间的子字符串的长度。

for(int i=0; i > stringLength - 1;){ 
original.substring(i, original.indexOf(' ')); 
if(i > minLength) 
+0

我不明白你想干什么?你想删除标点符号并获得字符串的长度吗? – denis

+0

我必须得到一个字符串中每个单词的长度。 –

回答

0

虽然它可能是诱人抛出一堆维权的和IFS,这将是清洁剂只使用正则表达式:

Pattern.compile("[.,; ]+").splitAsStream(input) 

完整的例子:

import java.util.regex.Pattern; 
import java.util.stream.Collectors; 

public class Counting { 
    public static void main(String... args) { 
     String text = "This is a string. With some punctuation, but I only care about words."; 

     String wordsWithLengths = Pattern.compile("[.,; ]+") 
       .splitAsStream(text) 
       .map(word -> word + " => " + word.length()) 
       .collect(Collectors.joining("\n")); 

     System.out.println(wordsWithLengths); 
    } 
} 

输出:

This => 4 
is => 2 
a => 1 
string => 6 
With => 4 
some => 4 
punctuation => 11 
but => 3 
I => 1 
only => 4 
care => 4 
about => 5 
words => 5 

另外,如果你想算多少的话有N多角色越多,你可以:

import java.util.regex.Pattern; 

public class CountingWords { 
    public static void main(String... args) { 
     String text = "This is a string. With some punctuation, but I only care about words."; 

     int threshold = 5; 
     long amountOfWords = Pattern.compile("[.,; ]+") 
       .splitAsStream(text) 
       .filter(word -> word.length() > threshold) 
       .count(); 

     System.out.println("There are " + amountOfWords + " words with more than " + threshold + " characters"); 
    } 
} 
+0

认为'\ W'匹配所有非单词字符 – njzk2

+0

我没有添加'\ W',因为它也会包含有效的字符,如' 'á'在其他语言。 – Logain

+0

我在编译时遇到了问题,能否帮我使用我使用的变量,因为我不确定哪里会发生什么: –

0

如果您只是需要得到每个字比这个会做的长度,否则,你这样做opertaion中如果statment:

int cnt = 0; 
for(int i=0; i < original.length();i++){ 
    if(",;:.?! ".indexOf(orignal.charAt(i)) > -1){ 
     if(cnt > 0){ 
      System.out.println(cnt); 
      cnt = 0; 
     } 
    } else { 
     cnt++; 
    } 
} 
+0

为什么使用'indexOf'而不是'contains'? – njzk2

+0

如果您要发布代码,请尽量张贴不包含错误的代码,然后发送给您与其匹配的内容。两者在技术上相同 – Shashank

+0

如果您要发布代码,请尽量张贴不包含错误的代码。例如,FOR循环中的名为'original'的变量是一个Array ?.如果不是,那么它应该是:original.length()。这个indexof()方法是什么?我一直以为它是indexOf()方法;) – DevilsHnd