如何从字符串中修剪空格?

我正在为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(); } 

修剪前导和尾随空格的简单方法是调用String.trim() 。 如果你只想修剪前导空格和尾随空格(而不是所有前导空格和尾随空格),那么就有一个名为StringUtils.strip(String, String)的Apache commons方法可以做到这一点; 用" "作为第二个参数调用它。

您尝试过的代码存在许多错误,从根本上说效率很低。 如果您真的想自己实现,那么您应该:

  1. 计算前导空格字符
  2. 计算尾随空格字符
  3. 如果任一count不为零,则调用String.substring(from, end)创建一个包含要保留的字符的新字符串。

这种方法避免了复制任何字符1


1 – 实际上,这取决于String的实现。 对于某些实现,将不进行复制,对于其他实现,则进行单个复制。 但要么是你的方法的改进,需要至少2份,如果有任何字符需要修剪,则更多。

String.trim()非常老,至少对于java 1.3。 你没有这个?

首先,其他人对String.trim()看法。 真的,不要重新发明轮子。

但是为了记录,你的代码出了什么问题就是Java数组不能resize。 最初设置目标数组时,将其创建为0大小的数组。 然后告诉System.arraycopy在那里填充len - 1字符。 那不行。 如果您希望它工作,您需要将数组设置为:

 char[] newChars = new char[len - 1]; 

但这种效率极低,每次通过循环重新分配和复制一个新数组。 使用Stephen C提到的三个步骤,以substring结尾。

使用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. * 

* 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. *

* 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}. *

* 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()

这些案例可能是: –

 System.out.println("".strip()); System.out.println(" both ".strip()); System.out.println(" leading".strip()); System.out.println("trailing ".strip()); 

Apache StringUtils.strip是最适合所有预期空白字符(不仅仅是空格)的答案, 可以在这里下载 :

这里是从这个源文件中删除的相关代码,如果你愿意的话,可以在你自己的类中实现它,但实际上,只需下载并使用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); } 

如果您不想使用String.trim()方法,那么它可以像下面这样实现。 逻辑将处理不同的场景,如空格,制表符和其他特殊字符。

 public static String trim(String str){ int i=0; int j = str.length(); char[] charArray = str.toCharArray(); while((i 

目标数组newChars不足以容纳复制的值。 您需要将其初始化为要复制的数据的长度(因此,长度为1)。

你可以使用Guava CharMatcher 。

 String outputString = CharMatcher.whitespace().trimFrom(inputString); 

注意:这是有效的,因为空格全部在BMP中。