如何从字符串中删除所有空格?

huangapple go评论74阅读模式
英文:

How do I remove all whitespaces from a string?

问题

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

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.

英文:

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

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.

答案1

得分: 3

有两种 replace() 的方法 - 一种接受字符,另一种接受字符串。你正在使用字符类型,这就是为什么你不能指定一个 "nothing" 字符。

使用字符串版本:

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

还要注意我在那里纠正的错误:你的代码一遍又一遍地替换原始字符串中的字符,所以只有最后一次替换会生效。


你可以改成这样写:

public static String removeWhitespace(String s) {
    return s.replaceAll("\\s", ""); // 使用正则表达式
}
英文:

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.

Use the String verison:

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

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
}

答案2

得分: 1

以下是您提供的代码的翻译部分:

尝试这段代码

public class Main {
    public static void main(String[] args) throws Exception {
        String s = " Test example    hello string    replace  enjoy   hh ";
        System.out.println("原始字符串             :"+s);
        s = s.replace(" ", "");
        System.out.println("没有空格的最终字符串 :"+s);
    }
}

输出:

原始字符串              Test example    hello string    replace  enjoy   hh
没有空格的最终字符串 Testexamplehellostringreplaceenjoyhh

另一种方法是使用字符数组

public class Main {
    public static void main(String[] args) throws Exception {
        String s = " Test example    hello string    replace  enjoy   hh ";
        System.out.println("原始字符串             :"+s);
        String ss = removeWhitespace(s);
        System.out.println("没有空格的最终字符串 :"+ss);
      
    } 
    
    public static String removeWhitespace(String s) {
        char[] charArray = s.toCharArray();
        String gtg = "";
        
        for(int i =0; i<charArray.length; i++){                
            if ((charArray[i] != ' ') && (charArray[i] != '\t') &&(charArray[i] != '\n')) {
                gtg = gtg + charArray[i];
            }
        }    
        return gtg;
    }
}

输出:

原始字符串              Test example    hello string    replace  enjoy   hh
没有空格的最终字符串 Testexamplehellostringreplaceenjoyhh
英文:

Try this code,

public class Main {
    public static void main(String[] args) throws Exception {
        String s = &quot; Test example    hello string    replace  enjoy   hh &quot;;
        System.out.println(&quot;Original String             : &quot;+s);
        s = s.replace(&quot; &quot;, &quot;&quot;);
        System.out.println(&quot;Final String Without Spaces : &quot;+s);
    }
}

Output :

Original String             :  Test example    hello string    replace  enjoy   hh                                                                         
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh 

Another way by using char array :

public class Main {
    public static void main(String[] args) throws Exception {
        String s = &quot; Test example    hello string    replace  enjoy   hh &quot;;
        System.out.println(&quot;Original String             : &quot;+s);
        String ss = removeWhitespace(s);
        System.out.println(&quot;Final String Without Spaces : &quot;+ss);
      
    } 
    
    public static String removeWhitespace(String s) {
        char[] charArray = s.toCharArray();
        String gtg = &quot;&quot;;
        
        for(int i =0; i&lt;charArray.length; i++){                
            if ((charArray[i] != &#39; &#39;) &amp;&amp; (charArray[i] != &#39;\t&#39;) &amp;&amp;(charArray[i] != &#39;\n&#39;)) {
                gtg = gtg + charArray[i];
            }
        }    
        return gtg;
    }
}

Output :

Original String             :  Test example    hello string    replace  enjoy   hh                                                                         
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh

答案3

得分: 0

如果您想为 replace(char,char) 方法指定一个空字符,应该这样做:

public static String removeWhitespace(String s) {
    // 十进制格式或十六进制格式
    return s.replace(' ', (char) 0)
            .replace('\f', (char) 0)
            .replace('\n', (char) 0)
            .replace('\r', '\u0000')
            .replace('\t', '\u0000');
}

空字符仍然是一个字符,因此最好为 replace(CharSequence,CharSequence) 方法指定一个空字符串来删除这些字符:

public static String removeWhitespace(String s) {
    return s.replace(" ", "")
            .replace("\f", "")
            .replace("\n", "")
            .replace("\r", "")
            .replace("\t", "");
}

为了简化这段代码,您可以为 replaceAll(String,String) 方法指定一个正则表达式来删除所有空白字符

public static String removeWhitespace(String s) {
    return s.replaceAll("\\s", "");
}
英文:

If you want to specify an empty character for the replace(char,char) method, you should do it like this:

public static String removeWhitespace(String s) {
    // decimal format, or hexadecimal format
    return s.replace(&#39; &#39;, (char) 0)
            .replace(&#39;\f&#39;, (char) 0)
            .replace(&#39;\n&#39;, (char) 0)
            .replace(&#39;\r&#39;, &#39;\u0000&#39;)
            .replace(&#39;\t&#39;, &#39;\u0000&#39;);
}

But an empty character is still a character, therefore it is better to specify an empty string for the replace(CharSequence,CharSequence) method to remove those characters:

public static String removeWhitespace(String s) {
    return s.replace(&quot; &quot;, &quot;&quot;)
            .replace(&quot;\f&quot;, &quot;&quot;)
            .replace(&quot;\n&quot;, &quot;&quot;)
            .replace(&quot;\r&quot;, &quot;&quot;)
            .replace(&quot;\t&quot;, &quot;&quot;);
}

To simplify this code, you can specify a regular expression for the replaceAll(String,String) method to remove all whitespace characters:

public static String removeWhitespace(String s) {
    return s.replaceAll(&quot;\\s&quot;, &quot;&quot;);
}

<sup>See also:
<br>• Replacing special characters from a string
<br>• First unique character in a string using LinkedHashMap</sup>

huangapple
  • 本文由 发表于 2020年8月6日 00:56:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63269963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定