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

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

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

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


当前回答

请不要使用StringTokenizer类,因为它是出于兼容性原因而保留的遗留类,并且不鼓励在新代码中使用它。我们也可以使用其他人建议的拆分方法。

String[] sampleTokens = "004-034556".split("-");
System.out.println(Arrays.toString(sampleTokens));

正如预期的那样,它将打印:

[004, 034556]

在这个答案中,我还想指出Java8中拆分方法的一个变化。String#split()方法使用Pattern.split,现在它将删除结果数组开头的空字符串。请注意Java 8文档中的以下更改:

当输入开始时宽度匹配为正时序列,则在开头包含一个空前导子字符串生成的阵列。然而,开头的宽度为零永远不会产生这样的空前导子字符串。

对于以下示例,这意味着:

String[] sampleTokensAgain = "004".split("");
System.out.println(Arrays.toString(sampleTokensAgain));

我们将得到三个字符串:[0,0,4],而不是像Java7和以前的情况那样得到四个字符串。还要检查这个类似的问题。

其他回答

假设

拆分时不需要正则表达式您碰巧已经在应用程序中使用了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,因为它通常包含很多有用的东西。然而,如果除了执行拆分之外,您不需要它,那么实现自己或退出正则表达式是更好的选择。

有时,如果您想拆分包含+的字符串,那么它不会拆分;相反,您将得到一个运行时错误。在这种情况下,首先将+替换为_,然后拆分:

 this.text=text.replace("/", "_");
            String temp[]=text.split("_");

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

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

我使用了一个名为stringValue的字符串,它的形式类似于“那些有硬币的人,在雨中享受,那些有钞票的人正忙着寻找避难所”。

我将使用“,”作为冒号拆分stringValue。

然后,我只想使用三个不同TextView的SetText()来显示该字符串。

String stringValue = "Those who had coins, enjoyed in the rain, those who had notes were busy looking for the shelter";
String ValueSplitByColon[] = stringValue.split(",");

String firstValue = ValueSplitByColon[0];
String secondValue = ValueSplitByColon[1];
String thirdValue = ValueSplitByColon[2];

txtV1.setText(firstValue);
txtV2.setText(secondValue;
txtV3.setText(thirdValue;

其输出如下:

txtV1值是:那些有硬币的人txtV2值为:在雨中享受txtV3值是:那些有笔记的人正忙着寻找避难所

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

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

/**
 * 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;
}