2016-08-20 72 views
0

問題:我在Java中玩耍,我試圖計算字符串中連續的「字符」。Java字符串:檢查連續的字母或數字

實施例:

Scanner in = new Scanner(System.in); 
int n = in.nextInt(); 

String binaryString = Integer.toBinaryString(n); 

上面的代碼返回輸入的整數值的二進制字符串。如果我們輸入數字5,這將返回:101

我現在希望遍歷字符串並檢查字符串中是否有任何連續的1。

for (int i = 0; i < binaryString.lenth(); i++) 
{ 
    // code comes here... 
} 

我不知道該如何檢查。我曾嘗試以下:

for (int i = 0; i < binaryString.length(); i++) 
    { 
     char charAtPos = binaryString.charAt(i); 
     char charAtNextPos = binaryString.charAt(i+1); 
     if (charAtPos == '1') 
     { 
      if (charAtPos == charAtNextPos) 
      { 
       consecutive += 1; 
      } 
     } 
    } 

但這顯然拋出作爲的ArrayIndexOutOfBounds將i+1產生一個數比陣列長度大。

非常感謝您的回答。

歐文

+2

那麼在你的condidtion中如何使用binaryString.length() - 1? :) – kolboc

回答

1

你只需要1行:

binaryString.split("1(?=1)").length() - 1; 
+0

這是一個很好的答案。謝謝你有很多道理! –

2

嘗試運行for循環大小一個小於〜應變的長度

for (int i = 0; i < (binaryString.length()-1); i++) 
{ 
    char charAtPos = binaryString.charAt(i); 
    char charAtNextPos = binaryString.charAt(i+1); 
    if (charAtPos == '1') 
    { 
     if (charAtPos == charAtNextPos) 
     { 
      consecutive += 1; 
     } 
    } 
} 
+0

謝謝,這有幫助! –

+0

很高興,它幫助! –

0

我們可以使用仍然簡化代碼和操作員

import java.util.Scanner; 
    class StackBinary 
    { 
     public static void main(String args[]) 
     { 
      Scanner in = new Scanner(System.in); 
      String n = Integer.toBinaryString(in.nextInt()); 

      for (int i = 0; i < n.length()-1; i++) 
      { 
       char charAtPos = n.charAt(i); 
       char charAtNextPos = .charAt(i+1); 
       if (charAtPos == '1' && charAtNextPos == '1') 
       { 
        consecutive+=1; 
       }  
      } 
     } 
相關問題