如何以函数式的方式对字符串中特定索引之前的数字进行求和。

huangapple go评论77阅读模式
英文:

How to sum digits in String till specific index in functional way

问题

我想对例如String中的数字进行求和,例如"153",直到索引2,然后得到结果6,因为1+5=6。通常情况下,我会使用经典的循环解决方案,检查当前索引是否小于2:

static int sum(String s){
   int sum = 0;
    for(int i = 0; i < s.length() ; i++){
        if( Character.isDigit(s.charAt(i)) ){
            sum = sum + Character.getNumericValue(s.charAt(i));
        }
    }
    return sum;
}

上述方法运行正常,但我想将这个逻辑重写为Java的stream方法。

我有一个实现如下:

public static int sumDigitsTillIndex(String number) {
    return IntStream.range(0, number.length())
        .filter(i -> i < 2)
        .map(number::charAt)
        .sum();
}

对于参数153,我得到的结果是102,这对我来说很奇怪。

我找到了另一个类似的解决方案,如下:

return String
    .valueOf(number)
    .chars()
    .map(Character::getNumericValue)
    .sum();

这个解决方案可以正确求和数字,但使用额外的filter方法:

.filter(index -> number.charAt(index) < 2)

我得到以下错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 49

我将感激您提出如何修复上述两个解决方案,并获得一个可以对字符串中的数字进行求和直到特定索引的功能方法的建议。

英文:

I want to sum digits from eg. String like "153" till index 2 and receive result 6 because of 1+5=6.
In a normal way, I would use the classic loop solution like with check whether current index is lower than 2:

static int sum(String s){
       int sum = 0;
        for(int i = 0; i &lt; s.length() ; i++){
            if( Character.isDigit(s.charAt(i)) ){
                sum = sum + Character.getNumericValue(s.charAt(i));
            }
        }
        return sum;
}

Above approach works as it should but I want to rewrite this logic to Java stream approach.

I have an implementation like:

  public static int sumDigitsTillIndex(String number) {
    return IntStream.range(0, number.length())
        .filter(i -&gt; i &lt; 2)
        .map(number::charAt)
        .sum();
  }

and for this with argument 153 I am receiving 102 what is a surprise for me.

I have found another, smiliar solution like:

   return String
    .valueOf(number)
    .chars()
    .map(Character::getNumericValue)
    .sum();

which is summing numbers properly but with additional filter method like:
.filter(index -&gt; number.charAt(index) &lt; 2)
I am receiving
Exception in thread &quot;main&quot; java.lang.StringIndexOutOfBoundsException: String index out of range: 49

I will be grateful for suggestion on how to fix these two above solutions and receive functional approach which will sum up digits from String till particular index.

答案1

得分: 5

你可以这样做:

number.chars()
      .limit(2)
      .map(Character::getNumericValue)
      .sum();

或者

number.substring(0, 2)
      .chars()
      .map(Character::getNumericValue)
      .sum();
英文:

You can do:

number.chars()
      .limit(2)
      .map(Character::getNumericValue)
      .sum();

or

number.substring(0, 2)
            .chars()
            .map(Character::getNumericValue)
            .sum();

答案2

得分: 2

String.charAt(int) 返回一个字符,然后您将其封装为 Character。此外,您可以使用 limit 替代 filter。像这样,

return IntStream.range(0, number.length())
        .limit(2)
        .map(i -> Character.digit(number.charAt(i), 10))
        .sum();

对于请求的 &quot;153&quot;,这将返回 6

英文:

String.charAt(int) returns a character which you then box to a Character. Also, instead of filter you can use limit. Like,

return IntStream.range(0, number.length())
		.limit(2)
		.map(i -&gt; Character.digit(number.charAt(i), 10))
		.sum();

Which gives 6 for &quot;153&quot; as requested.

huangapple
  • 本文由 发表于 2020年5月3日 22:05:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/61575761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定