在 Java 中修剪字符串的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20291307/
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
Correct way to trim a string in Java
提问by Quest Monger
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?
那么我这样做对吗?
采纳答案by gpojd
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()
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 '\u0020' (the space character), then a reference to this String object is returned.
Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.
Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\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).
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.
修剪
公共字符串修剪()
返回字符串的副本,省略前导和尾随空格。如果此 String 对象表示一个空字符序列,或者此 String 对象表示的字符序列的第一个和最后一个字符的代码都大于 '\u0020'(空格字符),则返回对此 String 对象的引用。
否则,如果字符串中没有代码大于 '\u0020' 的字符,则创建并返回一个表示空字符串的新 String 对象。
否则,令 k 为代码大于 '\u0020' 的字符串中第一个字符的索引,并令 m 为代码大于 '\u0020' 的字符串中最后一个字符的索引。创建一个新的String对象,表示这个字符串的子串,以索引k处的字符开始,以索引m处的字符结束——即this.substring(k, m+1)的结果。
此方法可用于从字符串的开头和结尾修剪空格(如上定义)。
回报:
此字符串的副本,其中删除了前导和尾随空格,或者此字符串(如果它没有前导或尾随空格)。
回答by aga
As strings in Java are immutable objects, there is no way to execute trimming in-place. 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).
由于Java 中的字符串是不可变对象,因此无法就地执行修剪。修剪字符串唯一可以做的就是创建新的字符串修剪版本并返回它(这就是该trim()
方法所做的)。
回答by Bruce Chidester
The traditional approach is to use the trim method inline...for example:
传统的方法是使用内联的trim方法......例如:
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 的“礼物”是您不需要管理它。
回答by Isaac
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. Here is a good explanation: Immutability of Strings in Java.
是的,但是在垃圾收集器删除输入指向的原始值之前,仍然会有两个对象。Java 中的字符串是不可变的。这是一个很好的解释:Java 中字符串的不变性。
回答by Dario
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. 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).
在实践中,trim() 方法实现被优化,以便它仅在必要时创建(并返回)另一个变量。在其他情况下(当实际上不需要修剪时)它会返回对原始字符串的引用(在这种情况下,您实际上是在为其自身分配一个变量)。
Anyway trim() does not modify original string, so this is the right way to use it.
无论如何,trim() 不会修改原始字符串,所以这是使用它的正确方法。
回答by pnkjshrm30
If we have to trim a String without using trim(), split() methods of Java then following source code can be helpful.
如果我们必须在不使用trim()、Java 的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();
}
回答by Mahmoud Elebiary
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
回答by Basil Bourque
String::strip…
String::strip…
The old String::trim
method has a strange definitionof whitespace.
旧String::trim
方法对whitespace有一个奇怪的定义。
As discussed here, Java 11 adds new strip…
methods to the String
class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace
.
正如此处所讨论的,Java 11strip…
向String
该类添加了新方法。这些使用更 Unicode 精通的空格定义。请参阅 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 leadingor just the trailingwhitespace.