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?
我这样做对吗?
8 个解决方案
#1
17
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.
字符串常量;它们的值在创建之后无法更改。字符串缓冲区支持可变字符串。因为字符串对象是不可变的,所以它们可以被共享。
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.
返回字符串的副本,省略了前导空格和尾随空格。如果这个字符串对象表示一个空字符序列,或者由这个字符串对象表示的字符序列的第一个和最后一个字符都具有大于“\u0020”(空格字符)的代码,那么返回这个字符串对象的引用。
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.
否则,如果字符串中没有具有大于“\u0020”代码的字符,则创建并返回一个表示空字符串的新字符串对象。
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).
否则,让k作为字符串中第一个字符的索引,其代码大于“\u0020”,并让m作为字符串中最后一个字符的索引,其代码大于“\u0020”。一个新的字符串对象被创建,它表示这个字符串的子字符串,它以索引k开头的字符开始,以索引m结束,也就是这个结果。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.
该字符串的一个拷贝,如果没有前导或尾随空白,则删除该字符串,或删除该字符串。
#2
9
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()方法所做的事情)。
#3
2
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).
在practice trim()方法实现中进行了优化,使它只在必要时创建(并返回)另一个变量。在其他情况(实际上不需要修剪)时,它将返回对原始字符串的引用(在本例中,实际上是为自己分配一个变量)。
看到http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java String.trim % 29 28%
Anyway trim() does not modify original string, so this is the right way to use it.
不管怎样,trim()不会修改原始字符串,所以这是正确的使用方法。
#4
1
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的“礼物”是您不需要管理它。
#5
1
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中字符串的不可变性。
#6
0
If we have to trim a String without using trim(), split() methods of Java then following source code can be helpful.
如果我们必须在不使用trim()、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();
}
#7
0
The java string trim() method eliminates leading and trailing spaces
java字符串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
#8
-1
This piece of code I did long back which takes a character array as parameter and returns a string. Little more modifications required for punctuations though with ascii values. Might be of some help.
我所做的这段代码将字符数组作为参数并返回一个字符串。虽然使用ascii值,但对标点符号的修改要少得多。可能会有帮助。
public static String trim(char [] input){
char [] output = new char [input.length];
int j=0;
int jj=0;
if(input[0] == ' ' ) {
while(input[jj] == ' ')
jj++;
}
for(int i=jj; i<input.length; i++){
if(input[i] !=' ' || ( i==(input.length-1) && input[input.length-1] == ' ')){
output[j]=input[i];
j++;
}
else if (input[i+1]!=' '){
output[j]=' ';
j++;
}
}
char [] m = new char [j];
int a=0;
for(int i=0; i<m.length; i++){
m[i]=output[a];
a++;
}
return new String (m);
}
#1
17
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.
字符串常量;它们的值在创建之后无法更改。字符串缓冲区支持可变字符串。因为字符串对象是不可变的,所以它们可以被共享。
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.
返回字符串的副本,省略了前导空格和尾随空格。如果这个字符串对象表示一个空字符序列,或者由这个字符串对象表示的字符序列的第一个和最后一个字符都具有大于“\u0020”(空格字符)的代码,那么返回这个字符串对象的引用。
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.
否则,如果字符串中没有具有大于“\u0020”代码的字符,则创建并返回一个表示空字符串的新字符串对象。
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).
否则,让k作为字符串中第一个字符的索引,其代码大于“\u0020”,并让m作为字符串中最后一个字符的索引,其代码大于“\u0020”。一个新的字符串对象被创建,它表示这个字符串的子字符串,它以索引k开头的字符开始,以索引m结束,也就是这个结果。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.
该字符串的一个拷贝,如果没有前导或尾随空白,则删除该字符串,或删除该字符串。
#2
9
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()方法所做的事情)。
#3
2
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).
在practice trim()方法实现中进行了优化,使它只在必要时创建(并返回)另一个变量。在其他情况(实际上不需要修剪)时,它将返回对原始字符串的引用(在本例中,实际上是为自己分配一个变量)。
看到http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java String.trim % 29 28%
Anyway trim() does not modify original string, so this is the right way to use it.
不管怎样,trim()不会修改原始字符串,所以这是正确的使用方法。
#4
1
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的“礼物”是您不需要管理它。
#5
1
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中字符串的不可变性。
#6
0
If we have to trim a String without using trim(), split() methods of Java then following source code can be helpful.
如果我们必须在不使用trim()、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();
}
#7
0
The java string trim() method eliminates leading and trailing spaces
java字符串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
#8
-1
This piece of code I did long back which takes a character array as parameter and returns a string. Little more modifications required for punctuations though with ascii values. Might be of some help.
我所做的这段代码将字符数组作为参数并返回一个字符串。虽然使用ascii值,但对标点符号的修改要少得多。可能会有帮助。
public static String trim(char [] input){
char [] output = new char [input.length];
int j=0;
int jj=0;
if(input[0] == ' ' ) {
while(input[jj] == ' ')
jj++;
}
for(int i=jj; i<input.length; i++){
if(input[i] !=' ' || ( i==(input.length-1) && input[input.length-1] == ' ')){
output[j]=input[i];
j++;
}
else if (input[i+1]!=' '){
output[j]=' ';
j++;
}
}
char [] m = new char [j];
int a=0;
for(int i=0; i<m.length; i++){
m[i]=output[a];
a++;
}
return new String (m);
}