有没有其他方法可以删除字符串中的所有空格? [英] Is there any other way to remove all whitespaces in a string?

查看:29
本文介绍了有没有其他方法可以删除字符串中的所有空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个编程作业.它说我需要先反转字符串,然后将其更改为大写,然后删除所有空格.我确实做到了,但是我们的教授并没有说使用 replaceAll() 方法.除了 replaceAll() 之外还有其他方法吗?

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()?

这是我的代码:

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", ""));
}

推荐答案

您可以使用 Character.isWhitespace 依次检查每个字符.此外,在循环内连接时,通常最好使用 StringBuilder.

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);
}

这篇关于有没有其他方法可以删除字符串中的所有空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆