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

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

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

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


当前回答

要拆分字符串,请使用string.split(正则表达式):

String phone = "004-034556";
String[] output = phone.split("-");
System.out.println(output[0]);
System.out.println(output[1]);

输出:

004
034556

其他回答

String s="004-034556";
for(int i=0;i<s.length();i++)
{
    if(s.charAt(i)=='-')
    {
        System.out.println(s.substring(0,i));
        System.out.println(s.substring(i+1));
    }
}

正如大家所提到的,split()是在您的案例中可能使用的最佳选项。另一种方法可以是使用substring()。

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

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

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

使用org.apache.commons.lang.StringUtils的拆分方法,该方法可以根据要拆分的字符或字符串拆分字符串。

方法签名:

public static String[] split(String str, char separatorChar);

在您的情况下,当出现“-”时,您希望拆分字符串。

您可以简单地执行以下操作:

String str = "004-034556";

String split[] = StringUtils.split(str,"-");

输出:

004
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和以前的情况那样得到四个字符串。还要检查这个类似的问题。

无论是否有任何类型的分隔符,您都可以简单地使用StringTokenizer将字符串拆分为两个或多个部分:

StringTokenizer st = new StringTokenizer("004-034556", "-");
while(st.hasMoreTokens())
{
    System.out.println(st.nextToken());
}