Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

java - Is there any other way to remove all whitespaces in a string?

I have a programming homework. It says that I need to reverse the string first, then change it to uppercase and then remove all the whitespaces. I actually did it, but our professor didn't say anything about using replaceAll() method. Is there any other way to do it beside replaceAll()?

Here is my code:

public static void main(String[] args) {
    String line = "the quick brown fox";
    String reverse = "";

    for (int i = line.length() - 1; i >= 0; i--) {
        reverse = reverse + line.charAt(i);
    }
    System.out.println(reverse.toUpperCase().replaceAll("\s", ""));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can check each character in turn using Character.isWhitespace. Additionally, it is generally better to use a StringBuilder when concatenating inside a loop.

public static void main(String[] args) {
    String line = "the quick brown fox";
    StringBuilder sb = new StringBuilder(line.length());

    for (int i = line.length() - 1; i >= 0; i--) {
        char c = line.charAt(i);
        if(!Character.isWhitespace(c)) sb.append(Character.toUpperCase(c));
    }
    System.out.println(sb);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...