簡體   English   中英

查找字符串中的整數個數(不是數字)

[英]finding number of integers in a string(not digits)

我正在嘗試計算字符串中整數的實際長度

我一直在使用這種方法來查找所有字符的長度

        whitespace = input.length() - input.replaceAll(" ", "").length();
        len = input.length()-whitespace;

但是問題是當字符串包含大於9的整數時

例如“ 1 2 3 456”,它應返回4個整數實例。

該段代碼的長度為6。

我發現的另一種方法是

        int counter = 0;
        for (int i = 0, length = input.length(); i < len; i++) {
            if (Character.isDigit(input.charAt(i))) {
                counter++;
            }
        }

但這也算數字,而不是整數。

如何隔離大於9的整數來計數?

String input = "1 2 3 456";

int len=input.split(" ").length;

這將使len為4。

您可以嘗試這樣-

int count = 0;
for(String s : input.split(" ")){
  if(isNumeric(s)) count++;
}


// method to check if string is a number
public boolean isNumeric(String s) {  
    return s.matches("[-+]?\\d*\\.?\\d+");  
} 

嘗試這個

    Matcher m = Pattern.compile("\\d+").matcher(s);
    int n = 0;
    while(m.find()) {
        n++;
    }
    System.out.println(n);

檢查此程序。

int count = 0;
for(String string : input.split(" ")){
  if(isInteger(string)) count++;
}

boolean isInteger( String string )  
{  
   try  
   {  
      Integer.parseInt( string );  
      return true;  
   }  
   catch( Exception )  
   {  
      return false;  
   }  
}

`

跟着這些步驟

  1. 在存在空格的地方拆分字符串.split(“”)
  2. 分割字符串為數組類型
  3. 現在計算每個拆分數組的長度
  4. 最后一步是添加所有長度(如果要計算整數數)
  5. 使用分割數組的長度方法來知道整數實例的數量

String x="1 2 24";
    String x1[]=x.split(" ");
    int l1=x1[0].length();
    int l2=x1[1].length();
    int l3=x1[2].length();
    System.out.println(l3+l1+l2);
System.out.println(x1.length());// this will give number of integers in the string

輸出 4

3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM