简体   繁体   English

在Java中修剪字符串的正确方法

[英]Correct way to trim a string in Java

In Java, I am doing this to trim a string: 在Java中,我这样做是为了修剪一个字符串:

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.trim();
System.out.println("after->>"+input+"<<-");

Output is: 输出是:

before->> some Thing <<-
after->>some Thing<<-

Works. 作品。 But I wonder if by assigning a variable to itself, I am doing the right thing. 但我想知道如果通过为自己分配一个变量,我做的是正确的。 I don't want to waste resources by creating another variable and assigning the trimmed value to it. 我不想通过创建另一个变量并为其分配修剪值来浪费资源。 I would like to perform the trim in-place. 我想在原地进行修剪。

So am I doing this right? 我这样做对吗?

You are doing it right. 你做得对。 From the documentation : 文档

Strings are constant; 字符串是不变的; their values cannot be changed after they are created. 它们的值在创建后无法更改。 String buffers support mutable strings. 字符串缓冲区支持可变字符串。 Because String objects are immutable they can be shared. 因为String对象是不可变的,所以可以共享它们。

Also from the documentation : 还来自文档

trim 修剪

public String trim() public String trim()

Returns a copy of the string, with leading and trailing whitespace omitted. 返回字符串的副本,省略前导和尾随空格。 If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\ ' (the space character), then a reference to this String object is returned. 如果此String对象表示空字符序列,或者此String对象表示的字符序列的第一个和最后一个字符的代码都大于'\\ u0020'(空格字符),则返回对此String对象的引用。

Otherwise, if there is no character with a code greater than '\ ' in the string, then a new String object representing an empty string is created and returned. 否则,如果字符串中没有代码大于'\\ u0020'的字符,则会创建并返回表示空字符串的新String对象。

Otherwise, let k be the index of the first character in the string whose code is greater than '\ ', and let m be the index of the last character in the string whose code is greater than '\ '. 否则,令k为代码大于'\\ u0020'的字符串中第一个字符的索引,并且令m为代码大于'\\ u0020'的字符串中最后一个字符的索引。 A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1). 创建一个新的String对象,表示该字符串的子字符串,该字符串以索引k处的字符开头,以索引m处的字符结尾,即this.substring(k,m + 1)的结果。

This method may be used to trim whitespace (as defined above) from the beginning and end of a string. 此方法可用于从字符串的开头和结尾修剪空白(如上所述)。

Returns : 退货

A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space. 删除了前导和尾随空格的此字符串的副本,如果没有前导或尾随空格,则为此字符串。

As strings in Java are immutable objects , there is no way to execute trimming in-place. 由于Java中的字符串是不可变对象 ,因此无法就地执行修剪。 The only thing you can do to trim the string is create new trimmed version of your string and return it (and this is what the trim() method does). 修剪字符串唯一可以做的就是创建字符串的新修剪版本并返回它(这就是trim()方法的作用)。

In theory you are not assigning a variable to itself. 理论上,您不是为自己分配变量。 You are assigning the returned value of method trim() to your variable input. 您将方法trim()的返回值赋给变量输入。

In practice trim() method implementation is optimized so that it is creating (and returning) another variable only when necessary. 实际上,trim()方法实现已经过优化,因此它只在必要时创建(并返回)另一个变量。 In other cases (when there is actually no need to trim) it is returning a reference to original string (in this case you are actually assigning a variable to itself). 在其他情况下(当实际上不需要修剪时)它返回对原始字符串的引用(在这种情况下,您实际上是为自己分配变量)。

See http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.trim%28%29 请参阅http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.trim%28%29

Anyway trim() does not modify original string, so this is the right way to use it. 无论如何trim()不会修改原始字符串,所以这是使用它的正确方法。

The traditional approach is to use the trim method inline...for example: 传统方法是使用内联修剪方法...例如:

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
System.out.println("after->>"+input.trim()+"<<-");

If it is a string that should be trimmed for all usages, trim it up front like you have done. 如果它是一个应该为所有用途进行修剪的字符串,请像往常一样修剪它。 Re-using the same memory location like you have done is not a bad idea, if you want to communicate your intent to other developers. 如果您想将您的意图传达给其他开发人员,重新使用与您相同的内存位置并不是一个坏主意。 When writing in Java, memory managment is not they key issue since the "gift" of Java is that you do not need to manage it. 使用Java编写时,内存管理不是关键问题,因为Java的“礼物”是您不需要管理它。

Yes, but there will still be two objects until the garbage collector removes the original value that input was pointing to. 是的,但是在垃圾收集器删除输入指向的原始值之前,仍然会有两个对象。 Strings in Java are immutable. Java中的字符串是不可变的。 Here is a good explanation: Immutability of Strings in Java . 这是一个很好的解释: Java中字符串的不变性

String::strip…

The old String::trim method has a strange definition of whitespace . 旧的String::trim方法有一个奇怪空格 定义

As discussed here , Java 11 adds new strip… methods to the String class. 正如这里所讨论的,Java 11为String类添加了新的strip…方法。 These use a more Unicode-savvy definition of whitespace. 这些使用了更精通Unicode的空白定义。 See the rules of this definition in the class JavaDoc for Character::isWhitespace . 请参阅类JavaDoc for Character::isWhitespace的此定义的规则。

Example code. 示例代码。

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");

Or you can strip just the leading or just the trailing whitespace. 或者你可以删除前导只是尾随空格。

If we have to trim a String without using trim(), split() methods of Java then following source code can be helpful. 如果我们必须修剪一个String而不使用Java的split(),split()方法,那么下面的源代码可能会有所帮助。

static String allTrim(String str)
{
    int j = 0;
    int count = 0;  // Number of extra spaces
    int lspaces = 0;// Number of left spaces
    char ch[] = str.toCharArray();
    int len = str.length();
    StringBuffer bchar = new StringBuffer();
    if(ch[0] == ' ')
    {
        while(ch[j] == ' ')
        {
            lspaces++;
            j++;
        }   
    }   
    for(int i = lspaces; i < len; i++)
    {   
        if(ch[i] != ' ')
        {
            if(count > 1 || count == 1)     
            {
                bchar.append(' ');
                count = 0;
            }
            bchar.append(ch[i]);
        }
        else if(ch[i] == ' ')
        {
            count++;    
        }
    }
    return bchar.toString();
}

The java string trim() method eliminates leading and trailing spaces java string trim()方法消除了前导和尾随空格

public class StringTrimExample{  
public static void main(String args[]){  
String s1="  hello string   ";  
System.out.println(s1+"javatpoint");//without trim()  
System.out.println(s1.trim()+"javatpoint");//with trim()  
}}  

output 产量

 hello string   javatpoint
hello stringjavatpoint   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM