我想通过分隔符“-”将字符串“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");
    }
}

其他回答

可以使用以下语句通过换行符拆分字符串:

String textStr[] = yourString.split("\\r?\\n");

可以使用以下语句按连字符/字符拆分字符串:

String textStr[] = yourString.split("-");

这:

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

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

根据文档:

public String[]split(Stringregex,int limit)围绕给定正则表达式的匹配项拆分此字符串。此方法返回的数组包含此字符串的子字符串,该子字符串由另一个与给定表达式匹配或以一串数组中的子字符串的顺序如下出现在此字符串中。如果表达式与输入,则结果数组只有一个元素,即一串

基本上你可以这样做:

String s = "123-456-789-123"; // The String to be split
String[] array = s.split("-"); // Split according to the hyphen and put them in an array
for(String subString : array){ // Cycle through the array
   System.out.println(subString);
}

输出:

123
456
789
123

使用Java 8:

    List<String> stringList = Pattern.compile("-")
            .splitAsStream("004-034556")
            .collect(Collectors.toList());

    stringList.forEach(s -> System.out.println(s));

我使用了一个名为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值是:那些有笔记的人正忙着寻找避难所