2016-11-06 139 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