Java 使用一个简单的扫描仪,读取一个带空格的字符串,为什么 .trim() 方法不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4442702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:34:00  来源:igfitidea点击:

Using a simple scanner, reading a string with spaces, how come .trim() method isn't working?

javastringtrim

提问by WM.

import java.util.Scanner;
import java.lang.String;

public class Test
{
    public static void main(String[] args)
    {
        char[] sArray;

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a Palindrome : ");
        String s = scan.nextLine();
        s = s.trim();

        sArray = new char[s.length()];

        for(int i = 0; i < s.length(); i++)
        {
            sArray[i] = s.charAt(i);
            System.out.println(sArray[i]);
        }
    }
}

采纳答案by jjnguy

Trim doesn't work how you expect it to. trim()only removes whitespace from the ends of the string.

Trim 不能像您期望的那样工作。 trim()只从字符串的末尾删除空格。

The documentation for trim():

文档trim()

Returns a copy of the string, with leadingand trailingwhitespace omitted.

返回字符串的副本,省略前导尾随空格。

To remove all whitespace try the following instead of calling trim():

要删除所有空格,请尝试以下操作而不是调用trim()

s = s.replaceAll("\s+", "");

This uses a very simple regular expression to remove all whitespace anywhere in the string.

这使用一个非常简单的正则表达式来删除字符串中任何位置的所有空格。

回答by SLaks

The trimfunction removes leading and trailingspaces, not all spaces.

trim函数删除前导和尾随空格,而不是所有空格。

If you want to remove all spaces, you can call s = s.replaceAll(" ", "").

如果要删除所有空格,可以调用s = s.replaceAll(" ", "").

回答by Ted Betz

great answer jjnguy and slals

很好的答案 jjnguy 和 slals

I now use

我现在用

myinput = myEditTextbox.getText().toString;
myinput = myinput.replaceAll("\S+", "");

to clean out all spaces accidentally left in an edittext box by the user. It also directed me to learn about regular expressions that I didn't know about. Thanks

清除用户意外留在编辑文本框中的所有空间。它还指导我学习我不知道的正则表达式。谢谢