How to get sum of char values produced in a loop?

后端 未结 5 1119
迷失自我
迷失自我 2021-01-22 09:45

Sorry if the title is misleading or is confusing, but here is my dilemma. I am inputting a string, and want to assign a value to each capitalized letter in the alphabet (A=1, ..

5条回答
  •  清酒与你
    2021-01-22 10:15

    Achieve the same in a concise way by employing Java 8's lambda functions

    String str = "ABCD";
    int sum = str.chars()
                    .filter(c -> c >= 'A' && c <= 'Z')
                    .map(c -> 1 + c - 'A')
                    .reduce(0, Integer::sum);
    

提交回复
热议问题