[英]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;
}
}
`
跟着這些步驟
例
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.