如何从字符串中修剪空格? [英] How to trim the whitespace from a string?
问题描述
我正在为J2ME应用程序编写这个函数,所以我没有一些更高级/现代的Java类可供我使用。我在这上面得到 java.lang.ArrayIndexOutOfBoundsException
。所以,显然要么它不喜欢我初始化 newChars
数组的方式,要么在调用 System时我没有做正确的事情。 arraycopy
。
I am writing this function for a J2ME application, so I don't have some of the more advanced / modern Java classes available to me. I am getting java.lang.ArrayIndexOutOfBoundsException
on this. So, apparently either it doesn't like the way I've initialized the newChars
array, or I'm not doing something correctly when calling System.arraycopy
.
/*
* remove any leading and trailing spaces
*/
public static String trim(String str) {
char[] chars = str.toCharArray();
int len = chars.length;
// leading
while ( (len > 0 ) && ( chars[0] == ' ' ) ) {
char[] newChars = new char[] {}; // initialize empty array
System.arraycopy(chars, 1, newChars, 0, len - 1);
chars = newChars;
len = chars.length;
}
// TODO: trailing
return chars.toString();
}
推荐答案
修剪领先的简单方法和尾随空格是调用 String.trim()
。如果你只想修剪前导和尾随空格(而不是所有前导和尾随空格),那么有一个名为 StringUtils.strip(String,String)
可以做到这一点;用作为第二个参数调用它。
The simple way to trim leading and trailing whitespace is to call String.trim()
. If you just want to trim just leading and trailing spaces (rather than all leading and trailing whitespace), there is an Apache commons method called StringUtils.strip(String, String)
that can do this; call it with " "
as the 2nd argument.
你试过的代码有很多bug,从根本上来说效率低下。如果你真的想自己实现,那么你应该:
Your attempted code has a number of bugs, and is fundamentally inefficient. If you really want to implement this yourself, then you should:
- 计算领先的空格字符
- 计算尾随空格字符
- 如果其中一个计数非零,则调用
String.substring(from,end)
创建一个包含您要保留的字符的新字符串。
- count the leading space characters
- count the trailing space characters
- if either count is non-zero, call
String.substring(from, end)
to create a new string containing the characters you want to keep.
此方法可避免复制任何字符 1 。
This approach avoids copying any characters1.
1 - 实际上,这取决于 String
。对于某些实现,将不进行复制,对于其他实现,则进行单个复制。但要么是你的方法的改进,需要至少2份,如果有任何要修剪的字符,则更多。
1 - Actually, that depends on the implementation of String
. For some implementations there will be no copying, for others a single copy is made. But either is an improvement on your approach, which entails a minimum of 2 copies, and more if there are any characters to trim.
这篇关于如何从字符串中修剪空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!