2017-03-06 24 views
3

我想檢查字符串是否有超過2次的特殊字符。
我取得的字符串使用下面的代碼是從列表:如何檢查字符串是否在java中有超過2個連續的特殊字符?

List <String> lst; 
for(String str: lst) 
{ 
System.out.println(str); 
} 

說輸入例:

This is sample example. 
######################## 
This will help you for sure 
"my friend" do not ask to delay more. 
$$200 not much 
sssssss 
better to go home. 

我想有輸出是這樣的:

This is sample example. 
This will help you for sure 
"my friend" do not ask to delay more. 
$$200 not much 
better to go home. 

如何我可以用JAVA實現這個輸出嗎?請提出一個方法。

+0

所以你給的例子是單個字符串('\ n')還是他們是不同的輸入? –

+0

@AnandUndavia這些是不同的字符串。逐行。 –

+0

@AnandUndavia你可以看到我編輯的問題一次。 –

回答

1

試試這個正則表達式: ​​

+0

表達式的解釋最有可能對OP也有幫助。 – DevilsHnd

+0

您的評論正則表達式爲我工作像魅力... :)謝謝。 –

-1

創建一個char數組,並搜索每個查看是否出現3個特殊字符,如果是這樣刪除(或者在我的情況下,不要將該字符串複製到將用於打印的newList中。 SSSSSSSS字符串,因爲它不是特殊字符,但你可以做到這一點,如果你做一個額外的,如果和檢查,如果連續3個字符具有相同的價值。

public static void main(String[] args) { 
     List <String> lst = new ArrayList<>(); 
     List <String> newList = new ArrayList<>(); 
     lst.add("This is sample example."); 
     lst.add("########################"); 
     lst.add("This will help you for sure"); 
     lst.add("\"my friend\" do not ask to delay more."); 
     lst.add("$$200 not much"); 
     lst.add("sssssss"); 
     lst.add("better to go home."); 

     for(int i = 0; i < lst.size(); i++) { 
      boolean keep = true; 
      char[] c = lst.get(i).toCharArray(); 
      for(int j = 0; j < c.length; j++) { 

//the following line can be edited based on what you consider special characters 

//但是這將允許所有的數字和字母

   if(j+2 < c.length && (c[j] < 48 || c[j] > 122 ||(c[j] > 57 && c[j] < 65))) { 
        if(c[j+1] < 65 || c[j+1] > 122 ||(c[j] > 57 && c[j] < 65)) { 
         if(c[j+2] < 65 || c[j+2] > 122 ||(c[j] > 57 && c[j] < 65)) { 
          keep = false; 
         } 
        } 
       } 
      } 
      if(keep) { 
       newList.add(lst.get(i)); 
      } 
     } 

     for(String str: newList) 
    { 
    System.out.println(str); 
    } 
    } 
+0

這可能會更好,如果你調用另一種方法,並使用遞歸我敢肯定,而不是使用三重if語句。這只是我發生的第一件事。 – Mellow

+0

爲什麼反對投票?它爲我運行,我誤解你的問題? – Mellow

+0

請再次閱讀我的問題。而且我沒有降低你的評價。你的回答不是什麼令我滿意的問題。因此,你可能會得到贊成票。 –

相關問題