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

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

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

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


当前回答

如果要验证字母数字,请将正则表达式更改为[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");
    }
}

其他回答

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

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 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()。

如果要验证字母数字,请将正则表达式更改为[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");
    }
}

Use:

String[] result = yourString.split("-");
if (result.length != 2) 
     throw new IllegalArgumentException("String not in correct format");

这将把你的绳子分成两部分。数组中的第一个元素将是包含-之前的内容的部分,数组中的第二个元素将包含-之后的字符串部分。

如果数组长度不是2,则字符串的格式不是:string string。

查看String类中的split()方法。

这:

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

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