2017-09-23 74 views
0

基本上,我被要求編寫一個程序來檢查一個數字在一個字符串中出現的次數並將其打印出來。這是我的有沒有更好的方法來檢查字符串中的任何數字?

BufferedReader input = new BufferedReader (new InputStreamReader (System.in)); 
    System.out.println("Please enter your string"); 
    String s = input.readLine(); 
    /*System.out.println("Please enter the chracter you are looking for"); 
    char c = (char)input.read();*/ 
    char one = '1'; 
    char two = '2'; 
    char three = '3'; 
    char four = '4'; 
    char five = '5'; 
    char six = '6'; 
    char seven = '7'; 
    char eight = '8'; 
    char nine = '9'; 
    char zero= '0'; 
int counter = 0; 
for(int i=0; i<s.length(); i++) { 
    if(s.charAt(i) == one || s.charAt(i) == two || s.charAt(i) == three || s.charAt(i) == four || 
s.charAt(i) == five || s.charAt(i) == six || s.charAt(i) == seven 
|| s.charAt(i) == eight || s.charAt(i) == nine || s.charAt(i) == zero) { 
     counter++; 


    } 


} 

有沒有更快,更好的方法來做到這一點?我嘗試另一種方式,但這個錯誤

Error: The operator || is undefined for the argument type(s) boolean, char 
+1

請爲編程語言添加標籤。 – miroxlav

回答

0

而是在代碼中聲明自己的數字,你可以看看在Java中Character.isDigit()方法。這將使代碼更清潔。沒有其他更快的方法來做到這一點。

如果要計算每個數字的出現位置,一種簡單的方法是使用Java地圖。您可以閱讀關於來自here的地圖的基本教程。

0

這部作品在C#

foreach (char c in str) 
    { 
     if (c >= '0' && c <= '9') 
      counter++; 
    } 
+0

OP尋找java的解決方案。 – soorapadman

0

您可以使用字符的十進制值(如ASCII table定義)

String s = "abc123def456"; 
int cpt = 0; 
for (int i = 0; i < s.length(); i++) { 
    if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { 
     cpt++; 
    } 
} 
System.out.println(cpt); // 6 

您還可以使用Character::isDigit方法

if (Character.isDigit(s.charAt(i))) { 
    cpt++; 
} 

編輯:

如果您使用的是Java 8 +,則可以將字符串轉換爲字符流,應用過濾器來保留數字,然後計算其中的元素數。

long nbDigits = s.chars() 
    .filter(Character::isDigit) // If the character is a digit (= the isDigit() method returns true) it's kept in the stream 
    .count(); 
System.out.println(nbDigits); // 6 
0

是有一個更快,更好的方式來做到這一點

你的做法是正確的絕對和幾乎最大快!你可以讓它變得可讀。

我認爲一般的算法是所有語言的相同與O(n)

  1. 循環數組和增量計數器,當發現一些字符。

您的方法是絕對正確的,幾乎是最快的!筆記:我真的認爲兩個比較和九個之間的速度非常小,我們不應該關心它)所有你能做的只是用盡可能少的代碼行編寫它。你可以做如下更正:

  1. char是在JVM整數和ASCII碼0-90x30-0x39,這樣你就可以擺脫==ch >= '0' && ch <= '9'
  2. 字符類包含檢查它的特殊方法:Character.isDigit(ch)
  3. 對於java 8,您可以使用Streams而不是手動for...each

不使用流(簡單Java)我認爲這種方法提供了最大的速度和酒糟存儲器對象

public int countDigits(String str) { 
    int count = 0; 

    for(int i = 0; i < str.length(); i++) 
     if(Character.isDigit(str.charAt(i))) 
      count++; 

    return count; 
} 

使用的流(從Java 8)。看起來不錯,比以前的例子慢一點,並在內存中創建一些額外的對象。

public int countDigits(String str) { 
    // could be a little bit slower, because additional objects are created inside 
    return (int)str.chars().filter(Character::isDigit).count(); 
} 

附:如果你想顯示你的技能,普通的老java變種是更可取的。在工作代碼中,兩種變體都是相同的。

P.P.S.實際String.toCharArray()str.chars()看起來更優雅,甚至執行得更少,因爲它們在內存中創建了額外的對象,但str.charAr(int)直接與內部陣列一起工作。但是我並沒有遇到實際應用中的任何方法問題

+2

你的第一個主張是錯誤的。 OP代碼爲每個i調用charAt(i)十次。如果你認爲這是「最快的」,那麼你和我的這兩個詞的意思就非常不同了。 – GhostCat

+0

@GhostCat +1。同意你。這不是絕對正確的。我修改了我的筆記。 –

相關問題