[Solved] How can we split the word into characters in android/java..?? and assign particular id to each character [closed]


I assume that you have maintained a map for mapping your characters with some numbers. Then you can simply split your string on empty string to get individual characters. And then iterate over your array to get the sum.

Note, that, splitting on empty string will get you an empty string as first element in array. Because, a string in Java contains an empty string at the start of string.

So, you can try out this code: –

    String str = "ABCDEF";
    String[] arr = str.split("");
    int sum = 0;

    Map<String, Integer> map = new HashMap<String, Integer>() {
        {
            put("A", 1); put("B", 2); put("C", 3);
            put("D", 4); put("E", 5); put("F", 6);
        }
    };

    System.out.println(Arrays.toString(arr));

    // Iteration starts from index 1, as 1st element is an empty string
    for (int i = 1; i < arr.length; i++) {
        sum += map.get(arr[i]);
    }

    System.out.println("Sum = " + sum);

OUTPUT: –: –

[, A, B, C, D, E, F]
Sum = 21

Or, you can also use String#toCharArray method, to directly convert your string into character array with individual characters. In that case, your map declaration should be like: – Map<Character, Integer>

String str = "ABCDEF";
Map<Character, Integer> map = new HashMap<Character, Integer>() {
        {
            put('A', 1); put('B', 2); put('C', 3);
            put('D', 4); put('E', 5); put('F', 6);
        }
};
for (char ch: str.toCharArray()) {
    sum += map.get(ch);
}

solved How can we split the word into characters in android/java..?? and assign particular id to each character [closed]