2017-02-03 66 views
2

檢查字符串長度的可能方法是什麼?等於最後附加的數字。我附上我寫的任何幫助表示讚賞的代碼。檢查字符串的長度是否等於最後附加的數字

public class Test { 

    public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    String str = "abcd10"; 
    String[] part = str.split("(?<=\\D)(?=\\d)"); 
    String strPart1 = part[0]; 
    int n = str.length(); 

     // Traverse string from end and find the number 
     // stored at the end. 
     // x is used to store power of 10. 
     int num = 0, x = 1, i = n-1; 

     for (i=n-1; i>=0; i--) { 
      char c = str.charAt(i); 
      if ('0' <= c && c <= '9') { 
       num = (c - '0')*x + num; 
       x = x * 10; 
       System.out.println("true"); 
      } else break; 
     }  
    } 
} 
+0

使用'模式'匹配整數。爲它獲取一個「匹配器」。 'start()'返回開始索引。 'group()'方法返回你的數字。 – soufrk

回答

1

你可以使用Integer.parseInt(String)與第二Stringpart陣列(10在您的文章)。然後檢查第一個元素的長度是否匹配。類似的,

String[] part = str.split("(?<=\\D)(?=\\d)"); 
int len = Integer.parseInt(part[1]); 
if (len == part[0].length()) { 
    System.out.printf("Yes. The length of %s is %d.%n", part[0], len); 
} else { 
    System.out.printf("No. The length of %s(%d) is not %d.%n", 
      part[0], part[0].length(), len); 
} 
0

您已經將字符串拆分爲兩部分,它們都存儲在part中。所以part[0]應該是"abcd"part[1]應該是"10"。因此,所有你需要做的是轉換part[1]到一個整數,該值比較的part[0]像這樣的長度,

int num = Integer.parseInt(part[1]); 
if(num == part[0].length()){ 
    System.out.println("true"); 
} 
0

使用計數器和內增加它的if

int digitCount = 0; 

if ('0' <= c && c <= '9') { 
    digitCount++; 
    ... 
} 

最後(在評估n之後,即後for循環)檢查

if(num == (n-digitCount)) { 
    System.out.println("Yes the length is same as the number at last."); 
} else ..not 
相關問題