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

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

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

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


当前回答

要拆分字符串,请使用string.split(regex)。查看以下示例:

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

输出

004
034556

注:

此拆分(正则表达式)以正则表达式作为参数。记住转义正则表达式特殊字符,如句点/点。

其他回答

String str="004-034556"
String[] sTemp=str.split("-");// '-' is a delimiter

string1=004 // sTemp[0];
string2=034556//sTemp[1];

如果要验证字母数字,请将正则表达式更改为[A-Za-z0-9]+-[A-Za-z 0-9]+

    public static final Pattern VALIDATE_PATTERN = Pattern.compile("[0-9]+-[0-9]+");

public static String[] validateString(String str) {
    if(VALIDATE_PATTERN.matcher(str).find()) {
        String[] output = str.split("-");
        if(output.length != 2) {
            throw new RuntimeException("Invalid string format");
        }
        return output;
    } else {
        throw new RuntimeException("Invalid string format");
    }
}

使用模式是Java 8。下面是路!!

package com.company;

import java.util.regex.Pattern;

public class umeshtest {

    public static void main(String a[]) {
        String ss = "I'm Testing and testing the new feature";
        Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
    }
}

这些要求为解释留下了空间。我建议写一个方法,

public final static String[] mySplit(final String s)

其封装了该功能。当然,您可以使用String.split(..),如实现的其他答案中所述。

您应该为输入字符串以及期望的结果和行为编写一些单元测试。

优秀的考生应包括:

 - "0022-3333"
 - "-"
 - "5555-"
 - "-333"
 - "3344-"
 - "--"
 - ""
 - "553535"
 - "333-333-33"
 - "222--222"
 - "222--"
 - "--4555"

通过定义相应的测试结果,您可以指定行为。

例如,如果“-333”应在[,333]中返回,或者如果它是一个错误。“333-333-33”是否可以在[333333-33]或[3333-333,33]中分开,或者这是一个错误?等等

这:

String[] out = string.split("-");

应该做你想做的事。string类有许多方法可用于字符串操作。