Skip to content

How to replace even values in string with ASCII value?

Suppose I have a string as ABCDEFG. I want to replace the even values of this string with their ASCII value. How should I do?

//STRING IS STORED IN str
for (int i = 0; i < str.length(); i++) {
    if (i % 2 != 0) { //FOR EVEN SPACES
        int m = str.charAt(i);
        //GOT ASCII VALUE OF even spaces
        System.out.println("Converted ASCII VALUES ARE" + m);
    }
}

Answer

You are almost there, you simply need to build the resulting string. Strings are immutable, so replacing would create a new String each time. I would suggest a StringBuilder for this task, but you can also do it manually.

The result would look like this:

public static void main(String[] args) {
    String str = "ABCDEF";
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        if (i % 2 != 0) {
            int m = str.charAt(i);
            sb.append(m); // add the ascii value to the string
        } else {
            sb.append(str.charAt(i)); // add the normal character
        }
    }
    System.out.println(sb.toString());
}

Output:

A66C68E70