Java 如何修剪字符串中的空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3796121/
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
How to trim the whitespace from a string?
提问by user458442
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
.
我正在为 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();
}
回答by Tony Ennis
String.trim()
is very old, at least to java 1.3. You don't have this?
String.trim()
很老了,至少到java 1.3。你没有这个?
回答by Stephen C
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.
修剪前导和尾随空格的简单方法是调用String.trim()
. 如果您只想修剪前导和尾随空格(而不是所有前导和尾随空格),则StringUtils.strip(String, String)
可以调用 Apache commons 方法来完成此操作;调用它" "
作为第二个参数。
Your attempted code has a number of bugs, and is fundamentally inefficient. If you really want to implement this yourself, then you should:
您尝试的代码有许多错误,而且从根本上说效率低下。如果你真的想自己实现这个,那么你应该:
- 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.
- 计算前导空格字符
- 计算尾随空格字符
- 如果任一计数不为零,则调用
String.substring(from, end)
以创建一个包含要保留的字符的新字符串。
This approach avoids copying any characters1.
这种方法避免了复制任何字符1。
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.
1 - 实际上,这取决于String
. 对于某些实现,将不进行复制,而对于其他实现,只进行一个副本。但要么是对您的方法的改进,至少需要 2 个副本,如果有任何字符需要修剪,则更多。
回答by Fredrick Pennachi
The destination array newChars is not large enough to hold the values copied. You need to initialize it to the length of the data you intend to copy (so, length - 1).
目标数组 newChars 不够大,无法保存复制的值。您需要将其初始化为要复制的数据的长度(因此,长度为 1)。
回答by Daniel Martin
First of all, what others said about String.trim()
. Really, don't reinvent the wheel.
首先,其他人怎么说String.trim()
。真的,不要重新发明轮子。
But for the record, what's going wrong with your code is that Java arrays aren't resizeable. When you initially set up your target array, you create it as a size 0 array. You then tell System.arraycopy
to stuff len - 1
characters in there. That's not going to work. If you wanted it to work, you'd need to set up the array as:
但是为了记录,您的代码出了什么问题是 Java 数组不能调整大小。最初设置目标数组时,将其创建为大小为 0 的数组。然后你告诉在那里System.arraycopy
填充len - 1
字符。那是行不通的。如果你想让它工作,你需要将数组设置为:
char[] newChars = new char[len - 1];
But that's amazingly inefficient, reallocating and copying a new array each time through the loop. Use the three steps that Stephen C mentioned, ending with a substring
.
但这是非常低效的,每次通过循环重新分配和复制一个新数组。使用 Stephen C 提到的三个步骤,以substring
.
回答by Brad Parks
Apache StringUtils.stripis the best answer here that works with all expected white space characters (not just space), and can be downloaded here:
Apache StringUtils.strip是这里最好的答案,它适用于所有预期的空白字符(不仅仅是空格),可以在这里下载:
Here's the relevant code ripped from this source fileto implement it in your own class if you wanted, but really, just download and use StringUtils to get more bang for your buck! Note that you can use StringUtils.stripStart
to trim any leading character from a java string as well.
这是从该源文件中提取的相关代码,如果您愿意,可以在您自己的类中实现它,但实际上,只需下载并使用 StringUtils 即可获得更多收益!请注意,您也可以使用StringUtils.stripStart
修剪 java 字符串中的任何前导字符。
public static final int INDEX_NOT_FOUND = -1
public static String strip(final String str) {
return strip(str, null);
}
public static String stripStart(final String str, final String stripChars) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
int start = 0;
if (stripChars == null) {
while (start != strLen && Character.isWhitespace(str.charAt(start))) {
start++;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while (start != strLen && stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND) {
start++;
}
}
return str.substring(start);
}
public static String stripEnd(final String str, final String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) {
end--;
}
}
return str.substring(0, end);
}
public static String strip(String str, final String stripChars) {
if (isEmpty(str)) {
return str;
}
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
回答by san242
If you don't want to use String.trim() method, then it can be implemented like below. The logic will handle different scenarios like space, tab and other special characters.
如果你不想使用 String.trim() 方法,那么它可以像下面这样实现。该逻辑将处理不同的场景,如空格、制表符和其他特殊字符。
public static String trim(String str){
int i=0;
int j = str.length();
char[] charArray = str.toCharArray();
while((i<j) && charArray[i] <=' '){
i++;
}
while((i<j) && charArray[j-1]<= ' '){
j--;
}
return str.substring(i, j+1);
}
public static void main(String[] args) {
System.out.println(trim(" abcd ght trip "));
}
回答by Naman
With JDK/11, now you can make use of the String.strip
API to return a string whose value is this string, with all leading and trailing whitespace removed. The javadoc for the same is :
使用 JDK/11,现在您可以使用String.strip
API 返回一个字符串,其值为该字符串,删除所有前导和尾随空格。同样的javadoc是:
/**
* Returns a string whose value is this string, with all leading
* and trailing {@link Character#isWhitespace(int) white space}
* removed.
* <p>
* If this {@code String} object represents an empty string,
* or if all code points in this string are
* {@link Character#isWhitespace(int) white space}, then an empty string
* is returned.
* <p>
* Otherwise, returns a substring of this string beginning with the first
* code point that is not a {@link Character#isWhitespace(int) white space}
* up to and including the last code point that is not a
* {@link Character#isWhitespace(int) white space}.
* <p>
* This method may be used to strip
* {@link Character#isWhitespace(int) white space} from
* the beginning and end of a string.
*
* @return a string whose value is this string, with all leading
* and trailing white space removed
*
* @see Character#isWhitespace(int)
*
* @since 11
*/
public String strip()
The sample cases for these could be:--
这些示例案例可能是:-
System.out.println("".strip());
System.out.println(" both ".strip());
System.out.println(" leading".strip());
System.out.println("trailing ".strip());
回答by sffc
You can use Guava CharMatcher.
您可以使用番石榴 CharMatcher。
String outputString = CharMatcher.whitespace().trimFrom(inputString);
Note: This works because whitespace is all in the BMP.
注意:这是有效的,因为空格都在 BMP 中。