Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to int using char array

how can I create a loop that also turns string "abcc" into the sum of their letter position, say a=1 b=2 c=3 and it sums the string 1+2+3+3=9.

    import java.util.Arrays;

    public class Test
    {
            public static void main(String[] args)
            {
            String original = "hello";
            char[] chars = original.toCharArray();
            Arrays.sort(chars);
            String sorted = new String(chars);
            System.out.println(sorted);


                }
           }
like image 281
Tok Doom Avatar asked Dec 21 '22 05:12

Tok Doom


1 Answers

You can use the ASCII values. a has value 97, b has 98 and so on.

private int printSum(String original){
    int sum = 0;
    if(original!=null){
        char[] arr = original.toLowerCase().toCharArray();
        for(int x :arr){
            sum+= (x-96);
        }
    }
    return sum;
}
like image 192
AllTooSir Avatar answered Feb 11 '23 17:02

AllTooSir