在Java中,我有一个这样的字符串:
" content ".
将String.trim()
删除这些边上的所有空格还是只删除每个空格?
从源代码(反编译):
public String trim()
{
int i = this.count;
int j = 0;
int k = this.offset;
char[] arrayOfChar = this.value;
while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
++j;
while ((j < i) && (arrayOfChar[(k + i - 1)] <= ' '))
--i;
return (((j > 0) || (i < this.count)) ? substring(j, i) : this);
}
您可以看到的两个while
表示所有 unicode 低于空格字符的字符,在开头和结尾都被删除。
如有疑问,请编写单元测试:
@Test
public void trimRemoveAllBlanks(){
assertThat(" content ".trim(), is("content"));
}
注意:当然测试(对于 JUnit + Hamcrest)不会失败
不过,需要指出的一件事是 String.trim 对“空白”有一个特殊的定义。它不会删除 Unicode 空格,但也会删除您可能不考虑空格的 ASCII 控制字符。
此方法可用于从字符串的开头和结尾修剪空白;事实上,它也会修剪所有 ASCII 控制字符。
如果可能,您可能希望使用 Commons Lang 的 StringUtils.strip(),它还可以处理 Unicode 空白(并且也是 null 安全的)。
请参阅String 类的API :
返回字符串的副本,省略前导和尾随空格。
两边的空格被删除:
注意trim()
不改变String实例,它会返回一个新对象:
String original = " content ";
String withoutWhitespace = original.trim();
// original still refers to " content "
// and withoutWhitespace refers to "content"
根据此处的 Java 文档,.trim()
替换通常称为空白的 '\u0020'。
但请注意,'\u00A0'(Unicode NO-BREAK SPACE
)也被视为空格,.trim()
不会删除它。这在 HTML 中尤其常见。
要删除它,我使用:
tmpTrimStr = tmpTrimStr.replaceAll("\\u00A0", "");
这里讨论了这个问题的一个例子。
Javatrim()
删除空格的示例:
public class Test
{
public static void main(String[] args)
{
String str = "\n\t This is be trimmed.\n\n";
String newStr = str.trim(); //removes newlines, tabs and spaces.
System.out.println("old = " + str);
System.out.println("new = " + newStr);
}
}
输出
old =
This is a String.
new = This is a String.
来自java docs(字符串类源),
/**
* Returns a copy of the string, with leading and trailing whitespace
* omitted.
* <p>
* If this <code>String</code> object represents an empty character
* sequence, or the first and last characters of character sequence
* represented by this <code>String</code> object both have codes
* greater than <code>'\u0020'</code> (the space character), then a
* reference to this <code>String</code> object is returned.
* <p>
* Otherwise, if there is no character with a code greater than
* <code>'\u0020'</code> in the string, then a new
* <code>String</code> object representing an empty string is created
* and returned.
* <p>
* Otherwise, let <i>k</i> be the index of the first character in the
* string whose code is greater than <code>'\u0020'</code>, and let
* <i>m</i> be the index of the last character in the string whose code
* is greater than <code>'\u0020'</code>. A new <code>String</code>
* object is created, representing the substring of this string that
* begins with the character at index <i>k</i> and ends with the
* character at index <i>m</i>-that is, the result of
* <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
* <p>
* This method may be used to trim whitespace (as defined above) from
* the beginning and end of a string.
*
* @return A copy of this string with leading and trailing white
* space removed, or this string if it has no leading or
* trailing white space.
*/
public String trim() {
int len = count;
int st = 0;
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[off + st] <= ' ')) {
st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}
请注意,在获取 start 和 length 之后,它会调用 String 类的 substring 方法。
trim()
将删除所有前导和尾随空格。但请注意:您的字符串没有更改。trim()
将返回一个新的字符串实例。
如果您的字符串输入是:
String a = " abc ";
System.out.println(a);
是的,输出将是“abc”;但是,如果您的字符串输入是:
String b = " This is a test "
System.out.println(b);
输出将是This is a test
所以修剪只删除字符串中第一个字符之前和最后一个字符之后的空格,并忽略内部空格。这是我的一段代码,它略微优化了内置的String
修剪方法,删除了内部空格,并删除了字符串中第一个和最后一个字符之前和之后的空格。希望能帮助到你。
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);
}
它将删除两侧的所有空格。
一件非常重要的事情是完全由“空格”组成的字符串将返回一个空字符串。
如果 a代表空格,string sSomething = "xxxxx"
将返回一个空字符串。x
sSomething.trim()
如果 a代表空格,string sSomething = "xxAxx"
将返回。x
sSomething.trim()
A
如果sSomething ="xxSomethingxxxxAndSomethingxElsexxx"
,sSomething.trim()
将返回SomethingxxxxAndSomethingxElse
,请注意x
单词之间的数量没有改变。
如果您想要一个整洁的打包字符串trim()
与正则表达式结合,如本文所示:如何使用 Java 删除字符串中的重复空格?.
顺序对结果没有意义,但trim()
首先会更有效率。希望能帮助到你。
要为字符串只保留一个实例,您可以使用以下内容。
str = " Hello ";
或者
str = str.trim();
然后str
字符串的值将是str = "Hello"
Trim() 适用于双方。
String 的Javadoc包含所有详细信息。从两端删除空格(空格、制表符等)并返回一个新字符串。
String formattedStr=unformattedStr;
formattedStr=formattedStr.trim().replaceAll("\\s+", " ");