Java - Write code to replace Whitespaces

Requirements

Write code to replace Whitespaces

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "b  oo k2s.com";
        System.out.println(replaceWhitespaces(string));
    }//from w  w  w .  j  a  va 2  s  .  c  o  m

    public static String replaceWhitespaces(String string) {
        StringBuilder builder = new StringBuilder(string);
        for (int i = 0; i < builder.length(); i++) {
            char c = builder.charAt(i);
            if (Character.isWhitespace(c))
                builder.setCharAt(i, '_');
        }
        return builder.toString();
    }
}

Related Exercise