想要在 Java String 上做左右修剪

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19130527/
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-12 14:21:58  来源:igfitidea点击:

Want to make left and right trim on Java String

java

提问by Vijay

I have Java String which contain white space on both right and left side. I want to remove white space from both side.

我有 Java 字符串,它在右侧和左侧都包含空格。我想从两边删除空白。

Code that I tried...

我试过的代码...

public class Test {

    public static void main(String args[])
    {
        String abc = "??Amebiasis  ";
        System.out.println(abc +" length "+abc.length());
        System.out.println(rtrim(abc)+" length "+rtrim(abc).length());
        System.out.println(ltrim(abc)+" length "+ltrim(abc).length());

        String ltrim = abc.replaceAll("^\s+","");
        String rtrim = abc.replaceAll("\s+$","");

        System.out.println("ltrim"+ltrim);
        System.out.println("rtrim"+rtrim);
    }

    public static String rtrim(String s) {
        int i = s.length()-1;
        while (i >= 0 && Character.isWhitespace(s.charAt(i))) {
            i--;
        }
        return s.substring(0,i+1);
    }

    public static String ltrim(String s) {
        int i = 0;
        while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
            System.out.println("s.charAt(i)  "+s.charAt(i));
            i++;
        }
        return s.substring(i);
    }
}

Output that I got... ?

我得到的输出...?

  Amebiasis   length 13
??Amebiasis length 11
??Amebiasis   length 13
ltrim??Amebiasis  
rtrim??Amebiasis

Somehow it doesn't remove white space. What is wrong with my code, please help me on that.

不知何故,它不会删除空白。我的代码有什么问题,请帮助我。

采纳答案by newuser

Defaultly available trim()

默认可用的trim()

String abc = "  Amebiasis  ";
System.out.println(""+abc.trim());

回答by aga

I've tried both of your functions, ltrimand rtrimand they work fine. If I understand you correctly, you expect that these functions will change the content of string in place. It's impossible, because strings in Java are immutable. If you wish to trim whitespaces from your string and then proceed to work with trimmed version of the string, you need to assign the value that rtrimor ltrimreturns to your abcvariable:

我都试过你的函数,ltrimrtrim和他们很好地工作。如果我理解正确,您会期望这些函数会在适当的位置更改字符串的内容。这是不可能的,因为 Java 中的字符串是不可变的。如果您希望从字符串中修剪空格,然后继续使用字符串的修剪版本,则需要将值rtrimltrim返回值分配给您的abc变量:

String abc = "  Amebiasis  ";
abc = rtrim(abc); // abc now equals to "  Amebiasis"
abc = ltrim(abc); // abc now equals to "Amebiasis"

回答by Mehmet Sedat Güng?r

You just need to assign the trimmed string object to a new string because Strings are immutable and trim() cannot edit that String while having same address. So;

您只需要将修剪后的字符串对象分配给新字符串,因为字符串是不可变的,并且在具有相同地址的情况下,trim() 无法编辑该字符串。所以;

String abc = "  Amebiasis  ";
String abcTrimmed = abc.trim();

should work.

应该管用。

回答by boumbh

Your code is working, the output in your question is wrong, the real output of your code is:

您的代码正在运行,您问题中的输出是错误的,您的代码的真实输出是:

  Amebiasis   length 13
  Amebiasis length 11
s.charAt(i)   
s.charAt(i)   
s.charAt(i)   
s.charAt(i)   
Amebiasis   length 11
ltrimAmebiasis  
rtrim  Amebiasis

If you only wish to trim both sides, just do

如果你只想修剪两边,就这样做

String abc = abc.trim();

回答by Nazar Ostryzhniuk

Use regex to remove all spaces from both sides:

使用正则表达式删除两边的所有空格:

return str.replaceAll("\s*$", "").replaceAll("^\s*", "");

回答by Kristian Kraljic

Using the Charactersclass, you can easily left / right trim any string for any given character(-class):

使用Characters类,您可以轻松地向左/向右修剪任何给定字符(-class)的任何字符串:

Characters.valueOf('x').trim( ... )
Characters.valueOf('x').leftTrim( ... )
Characters.valueOf('x').rightTrim( ... )

If you would like to trim for whitespaces, there is a predefined character-class available:

如果您想修剪空格,可以使用预定义的字符类:

Characters.WHITESPACE.trim( ... )
Characters.WHITESPACE.leftTrim( ... )
Characters.WHITESPACE.rightTrim( ... )

The class does feature also other kinds of character operations, such condense, replaceor split.

该类还具有其他类型的字符操作,例如condense,replacesplit

回答by Sushant Jain

You can simplify by using \\S*

您可以通过使用简化 \\S*

Example:

例子:

String name = "Hello      ::    World";
abc.replaceAll("\s*::\s*", "");

output will be

输出将是

HelloWorld