繁体   English   中英

计算Java中整数字符串中的位数

[英]Counting the number of digits in an integer string in Java

我有一个char数组(让我们说大小为4)。 我使用以下方法将其转换为字符串:

String str = String.valueOf(cf); // where cf is the char array of size 4.

此字符串可以包含0111001011等。现在,我需要计算此字符串中的位数。 但每次我计算数字位数(最好是在Java中)时,它会显示4作为结果(可能是由于大小为4)。 我该如何计算。 根据输入字符串的数字?

示例:如果001是输入,则应将o / p设为3,依此类推。

这是编码部分:

static long solve(int k, long n)
    {

  //  System.out.println("Entered Solve function");
  char[] c = new char[4];

  long sum = 0;
  char[] cf = {};

  for(long i=2;i<=n;i++)
  {

      cf = fromDeci(c, k, i);
      String str = String.valueOf(cf);


       //System.out.println(snew);
       sum = sum + str.length() ;
    }

  return sum;
}

您可以使用java 8中的Stream API, ONE-LINE中的解决方案:

String s = "101";
int nb = Math.toIntExact(s.chars()                     // convert to IntStream
                          .mapToObj(i -> (char)i)      // convert to char
                          .filter(ch -> isDigit(ch))   // keep the ones which are digits
                          .count());                   // count how any they are

使用正则表达式非常容易:

String test = "a23sf1";
int count = 0;
Pattern pattern = Pattern.compile("[0-9]");
Matcher  matcher = pattern.matcher(test);
while (matcher.find()) {
    count++;
}
System.out.println(count);

您可以通过与数字字符的简单比较来验证字符是否为数字。

private int countDigits(char[] cf) {
    int digitCt = 0; 
    for (char c : cf) {
        if ((c >= '0') && (c <= '9')) digitCt++;
    }
    return digitCt;
}

否则,您可以使用Apache Commons :(参见StringUtils

例如: StringUtils.getDigits("abc56ju20").size()

它给你4。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM