Java - Write code to Replace the character in str at index with replacement.

Requirements

Write code to Replace the character in str at index with replacement.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        int idx = 2;
        char replacement = 'a';
        System.out.println(replaceCharAtIdx(str, idx, replacement));
    }/*from w w w . ja  v  a  2s .  co  m*/

    /**
     * Replaces the character in str at idx with 
     *replacement.
     *
     * @param  str         The original String
     * @param  idx      An Integer representing the idx of the char being replaced.
     * @param  replacement   The char being inserted into str at idx.
     *
     * @return The new String with replacement at idx.
     *
     */
    public static String replaceCharAtIdx(String str, int idx,
            char replacement) {
        char array[] = str.toCharArray();
        array[idx] = replacement;
        str = new String(array);
        return str;
    }
}

Related Exercise