如何从字符串中删除所有空格? [英] How do I remove all whitespaces from a string?

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

问题描述

我正在尝试从字符串中删除所有空格.我在Google上搜索了很多,发现只有 replaceAll()方法用于删除空格.但是,在我正在做的在线课程作业中,它说使用 replace()方法删除所有空格,并使用 \ n 换行符和<代码> \ t (用于制表符).我试过了,这是我的代码:

I'm trying to remove all whitespaces from a string. I've googled a lot and found only replaceAll() method is used to remove whitespace. However, in an assignment I'm doing for an online course, it says to use replace() method to remove all whitespaces and to use \n for newline character and \t for tab characters. I tried it, here's my code:

public static String removeWhitespace(String s) {
    String gtg = s.replace(' ', '');
    gtg = s.replace('\t', '');
    gtg = s.replace('\n', '');
    return gtg;
}

编译后,出现错误信息:

After compiling, I get the error message:

Error:(12, 37) java: empty character literal
Error:(13, 37) java: empty character literal
Error:(14, 37) java: empty character literal

所有3个都在 public static String removeWhitespace(String s)中引用了上面的 replace()代码.如果有人指出我在做错事情,我将不胜感激.

All 3 refer to the above replace() code in public static String removeWhitespace(String s). I'd be grateful if someone pointed out what I'm doing wrong.

推荐答案

replace()有两种形式-一种采用字符形式,一种采用字符串形式.您使用的是char类型,这就是为什么您不能指定"nothing"的原因.字符.

There are two flavors of replace() - one that takes chars and one that takes Strings. You are using the char type, and that's why you can't specify a "nothing" char.

使用字符串版本:

gtg = gtg.replace("\t", "");

还请注意我在此处纠正的错误:您的代码会一遍又一遍地替换原始字符串中的char,因此只有最后一次替换会生效.

Notice also the bug I corrected there: your code replaces chars from the original string over and over, so only the last replace will be effected.

您可以直接编写以下代码:

You could just code this instead:

public static String removeWhitespace(String s) {
    return s.replaceAll("\\s", ""); // use regex
}

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

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