0

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);
    }
}
Abdullah
  • 3
  • 1
  • 4

2 Answers2

3

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
maloomeister
  • 2,461
  • 1
  • 12
  • 21
0
  • Method charAt returns char value at the specified index.
  • Method codePointAt returns unicode code point at the specified index.
String str = "ABCDEFG";

String str2 = IntStream.range(0, str.length())
        .mapToObj(i -> {
            if (i % 2 == 0)
                return String.valueOf(str.charAt(i));
            else
                return String.valueOf(str.codePointAt(i));
        }).collect(Collectors.joining());

System.out.println(str2); // A66C68E70G

See also: Change numbers to letters in a int array and return String