我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:

part1 = "004";
part2 = "034556";

这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。

我还想检查字符串中是否有“-”。


当前回答

我查看了所有答案,发现所有答案都是第三方许可或基于正则表达式的。

下面是我使用的一个很好的哑实现:

/**
 * Separates a string into pieces using
 * case-sensitive-non-regex-char-separators.
 * <p>
 * &nbsp;&nbsp;<code>separate("12-34", '-') = "12", "34"</code><br>
 * &nbsp;&nbsp;<code>separate("a-b-", '-') = "a", "b", ""</code>
 * <p>
 * When the separator is the first character in the string, the first result is
 * an empty string. When the separator is the last character in the string the
 * last element will be an empty string. One separator after another in the
 * string will create an empty.
 * <p>
 * If no separators are set the source is returned.
 * <p>
 * This method is very fast, but it does not focus on memory-efficiency. The memory
 * consumption is approximately double the size of the string. This method is
 * thread-safe but not synchronized.
 *
 * @param source    The string to split, never <code>null</code>.
 * @param separator The character to use as splitting.
 * @return The mutable array of pieces.
 * @throws NullPointerException When the source or separators are <code>null</code>.
 */
public final static String[] separate(String source, char... separator) throws NullPointerException {
    String[] resultArray = {};
    boolean multiSeparators = separator.length > 1;
    if (!multiSeparators) {
        if (separator.length == 0) {
            return new String[] { source };
        }
    }
    int charIndex = source.length();
    int lastSeparator = source.length();
    while (charIndex-- > -1) {
        if (charIndex < 0 || (multiSeparators ? Arrays.binarySearch(separator, source.charAt(charIndex)) >= 0 : source.charAt(charIndex) == separator[0])) {
            String piece = source.substring(charIndex + 1, lastSeparator);
            lastSeparator = charIndex;
            String[] tmp = new String[resultArray.length + 1];
            System.arraycopy(resultArray, 0, tmp, 1, resultArray.length);
            tmp[0] = piece;
            resultArray = tmp;
        }
    }
    return resultArray;
}

其他回答

使用适当命名的方法String#split()。

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

请注意,split的参数假定为正则表达式,因此如果需要,请记住转义特殊字符。

有12个字符具有特殊含义:反斜杠\、插入符号^、美元符号$、句点或点。,竖条或管道符号|,问号?,星号或星号*、加号+、左括号(,右括号)和左方括号[,左大括号{,这些特殊字符通常被称为“元字符”。

例如,在句点/点上拆分。(这在正则表达式中表示“任何字符”),使用反斜杠\转义单个特殊字符,如so split(“\\.”),或使用字符类[]表示文字字符,如“[.]”,或使用Pattern#quote()转义整个字符串,如so split(“.”)。

String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.

要预先测试字符串是否包含某些字符,只需使用string#contains()。

if (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}

注意,这不采用正则表达式。为此,请改用String#matches()。

如果您希望在生成的部分中保留拆分的字符,请使用正面环视。如果您希望拆分字符在左侧结束,请使用前缀?<=组。

String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

如果您希望拆分字符在右侧结束,请使用前置?=组。

String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

如果您想限制结果部分的数量,那么可以提供所需的数量作为split()方法的第二个参数。

String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42

假设

拆分时不需要正则表达式您碰巧已经在应用程序中使用了apachecommons-lang

最简单的方法是使用StringUtils#split(java.lang.String,char)。如果不需要正则表达式,这比Java提供的开箱即用更方便。正如其手册所说,它的工作原理如下:

A null input String returns null.

 StringUtils.split(null, *)         = null
 StringUtils.split("", *)           = []
 StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
 StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
 StringUtils.split("a:b:c", '.')    = ["a:b:c"]
 StringUtils.split("a b c", ' ')    = ["a", "b", "c"]

我建议使用commong lang,因为它通常包含很多有用的东西。然而,如果除了执行拆分之外,您不需要它,那么实现自己或退出正则表达式是更好的选择。

 String string = "004^034556-34";
 String[] parts = string.split(Pattern.quote("^"));

如果你有一个特殊的字符,那么你可以使用Pattern.quote。如果你只有破折号(-),那么你就可以缩短代码:

 String string = "004-34";
 String[] parts = string.split("-");

如果尝试添加其他特殊字符来代替短划线(^),则错误将生成ArrayIndexOutOfBoundsException。为此,您必须使用Pattern.quote。

你真正需要考虑的方法只有两种。

使用String.split作为一个字符分隔符,否则您不关心性能

如果性能不是问题,或者分隔符是不是正则表达式特殊字符的单个字符(即,不是.$|()[{^?*+\之一),则可以使用String.split。

String[] results = input.split(",");

如果delimeter是单个字符而不在上面的列表中,则split方法有一个优化,以避免使用正则表达式。否则,它必须编译正则表达式,这是不理想的。

如果使用复杂的分隔符并且您关心性能,请使用Pattern.split并预编译模式。

如果性能是一个问题,并且分隔符不是上述问题之一,那么应该预先编译一个正则表达式模式,然后可以重用它。

// Save this somewhere
Pattern pattern = Pattern.compile("[,;:]");

/// ... later
String[] results = pattern.split(input);

最后一个选项仍然会创建一个新的Matcher对象。您还可以缓存此对象并为每个输入重置它以获得最大性能,但这有点复杂,而且不线程安全。

对于简单的用例,String.split()应该完成这项工作。如果您使用番石榴,还有一个Splitter类,它允许链接不同的字符串操作并支持CharMatcher:

Splitter.on('-')
       .trimResults()
       .omitEmptyStrings()
       .split(string);