簡體   English   中英

在字符串Java中查找整數

[英]Finding Integers In a String java

我想編寫一個名為printDigit的方法,該方法應查找字符串中有多少個整數。

對於15 an1234d 16 man ,應返回2

那就是我絕望的代碼:)

public String printDigit() {
  String input = "15 an1234d 16 man";

  int len = input.split(" ").length;
  return len + "";
}

返回3 ,不應將an1234d視為整數。

您可以使用正則表達式:

(^|\s)\d+(\s|$)

這意味着:任意數量的數字,后跟一個空格(或字符串的開頭),然后是一個空格(或字符串的結尾)。

這是演示Java中用法的代碼段。 您可以在此處在線運行此代碼演示

public String printDigit() {
  String input = "15 an1234d 16 man";

  Pattern p = Pattern.compile("(^|\\s)\\d+(\\s|$)");
  Matcher m = p.matcher(input);
  int numberCount = 0;
  while(m.find()) {
      numberCount++;
  }

  return Integer.toString(numberCount);
}

輸出:

Numbers: 2

更新:每個注釋,使用parseInt()的替代方法:

請注意,在這種情況下使用parseInt()按Exception編碼的 (這被認為是不好的做法),但是如果必須使用Exception ,則可以使用下面的代碼段。 在此處在線運行

public static String printDigit() {
  String input = "15 an1234d 16 man";
  String[] tokens = input.split(" ");
  int numberCount = 0;
  for(String s : tokens) {
      try {
          Integer.parseInt(s);
          numberCount++;
      } catch (Exception e) { /* couldnt parse as integer, do nothing */ }
  }

  return Integer.toString(numberCount);
}

輸出:

Using parseInt(): 2

您可以使用org.apache.commons.lang.math.NumberUtils NumberUtils.isDigits(String str)方法。

檢查字符串是否僅包含數字字符。

public String printDigit() {
  String input = "15 an1234d 16 man";
  int numb = 0;
  for(String str : input.split(" ")){
    if(NumberUtils.isDigits(str))
       numb++;
  }
  return Integer.toString(numb);
}

您應該驗證Array中的每個值是否為NumberFormat

嘗試添加該功能:

String[] data= input.split(" ");
int k=0;

for(String str:data){
    try  
    {  
        double d = Double.parseDouble(str);  
        k++;
    }  
    catch(NumberFormatException nfe)  
    {  
        System.out.println("Not a number");
    }  
}
return k;

這是一個也支持負整數的非正則表達式解決方案(不使用.split() )。 它適用於所有測試用例,例如"-5 -3s0 1 s-2 -3-"

public int countInt(String s) {
    int count = 0;
    boolean isInt = false;
    boolean start = true;
    boolean neg;
    for (char n : s.toCharArray()) {
        if (start && Character.isDigit(n))
            isInt = true;
        neg = (n == '-') ? start : false;
        start = (n == ' ') ? true : neg;
        if (isInt && start)
            ++count;
        if (!Character.isDigit(n))
            isInt = false;
    }
    return count + (isInt ? 1 : 0);
}

它返回一個int而不是一個字符串:

> countInt("15 an1234d 16 man")
2
> countInt("-5 -3s0 1 s-2 -3-")
2

暫無
暫無

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

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