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

时间:2010-09-26 00:31:30

标签: java java-me

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

8 个答案:

答案 0 :(得分:37)

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

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

  1. 计算前导空格字符
  2. 计算尾随空格字符
  3. 如果任一计数非零,请致电String.substring(from, end)以创建包含您要保留的字符的新字符串。
  4. 这种方法避免复制任何字符 1


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

答案 1 :(得分:14)

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

答案 2 :(得分:4)

Apache StringUtils.strip是最适合所有预期空白字符(不仅仅是空格)和can be downloaded here的答案:

如果您愿意,可以在自己的类中使用相关代码ripped from this source file,但实际上,只需下载并使用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);
}

答案 3 :(得分:3)

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

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

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

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

答案 4 :(得分:3)

使用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()

这些案例可能是: -

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

答案 5 :(得分:1)

如果您不想使用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              "));

}

答案 6 :(得分:0)

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

答案 7 :(得分:0)

您可以使用Guava CharMatcher

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/test_chart"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="32dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />

</android.support.constraint.ConstraintLayout>

注意:这行得通,因为BMP中都包含空格。