Home Java Java-tips Data Strings Q-pr-string-using-loops Java: Delete Blanks - Solution

Ask Questions?

View Latest Questions

Advertisement


 
 

Java: Delete Blanks - Solution
Posted on: April 17, 2011 at 12:00 AM
This page discusses - Java: Delete Blanks - Solution

Java: Delete Blanks - Solution

See Exercise - Delete Blanks.

Solution 1 - Using charAt

public static String deblank(String s) {
    String result = "";
    for (int i=0; i<s.length(); i++) {
        if (s.charAt(i) != ' ') {
            result = result + s.charAt(i);
        }
    }
    return result;
}

Solution 2 - Using substring

public static String deblank(String s) {
    String result = "";
    for (int i=0; i<s.length(); i++) {
        if (!s.substring(i, i+1).equals(" ")) {
            result = result + s.substring(i, i+1);
        }
    }
    return result;
}

Other solutions

Other possible solutions use indexOf(), regular expresssions, etc.

Copyleft 2004 Fred Swartz MIT License
Advertisement


DMCA.com