我正在为 J2ME 应用程序编写此函数,因此我没有一些可用的更高级/现代的 Java 类。我正进入(状态java.lang.ArrayIndexOutOfBoundsException
关于这一点。所以,显然它不喜欢我初始化的方式newChars
数组,或者我在调用时没有正确执行某些操作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();
}
The simple way to trim leading and trailing whitespace is to call String.trim(). With Java 11 and later, you can also use String.strip() which uses a different interpretation of what "white space" means1.
如果您只想修剪前导和尾随空格(而不是所有前导和尾随空格),有一个 Apache commons 方法称为StringUtils.strip(String, String)可以做到这一点;调用它" "
作为第二个参数。
您尝试的代码有许多错误,并且从根本上来说效率很低。如果您真的想自己实现这一点,那么您应该:
- 计算前导空格字符
- 计算尾随空格字符
- 如果任一计数不为零,则调用
String.substring(from, end)
创建一个包含要保留的字符的新字符串。
This approach avoids copying any characters2.
1 - The different meanings are explained in the respective javadocs. Alternatively, read the answers to Difference between String trim() and strip() methods in Java 11.
2 - 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)