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

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

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

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


当前回答

使用模式是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));
    }
}

其他回答

这:

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

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

// This leaves the regexes issue out of question
// But we must remember that each character in the Delimiter String is treated
// like a single delimiter        

public static String[] SplitUsingTokenizer(String subject, String delimiters) {
   StringTokenizer strTkn = new StringTokenizer(subject, delimiters);
   ArrayList<String> arrLis = new ArrayList<String>(subject.length());

   while(strTkn.hasMoreTokens())
      arrLis.add(strTkn.nextToken());

   return arrLis.toArray(new String[0]);
}

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

方法签名:

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

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

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

String str = "004-034556";

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

输出:

004
034556

假设字符串中不存在-,则返回给定的字符串,并且不会出现任何异常。

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

Use:

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

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

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

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