通过其他方式拆分字符串

时间:2014-02-20 10:12:13

标签: java string

我有一个字符串“004-034556”,我想分成两个字符串:

string1 = "004"
string2 = "034556"

这意味着第一个字符串将包含“ - ”之前的字符,第二个字符串将包含“ - ”之后的字符。我还想检查字符串中是否包含“ - ”。如果没有,我会抛出异常。我怎么能这样做?

现在实现这一目标的一种方法是......

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]);
}

4 个答案:

答案 0 :(得分:2)

你可以这样做:

String str  = "004-034556";

if (str.contains("-")) { // Check if str contains "-"
    String strSplit[] = str.split("-");
}
else {
    // Throw exception
}

strSplit[0] ==&GT; 004

strSplit[1] ==&gt; 034556

答案 1 :(得分:1)

试试这个:

String[] spilited = abc.split("-");
if(spilited.size() == 0){
    throw new RuntimeException("String doesn't contain '-');
}

答案 2 :(得分:0)

String[] array = givenString.split("-");

并检查,

if(givenString.contains("-")) return true;

答案 3 :(得分:0)

public class SplitException extends Exception{
    ...
    ...
}

public String[] customSplit(String str, String splitter) {

    String[] splitted = str.split(splitter);
    if (splitted.size() == 0)
        throw new SplitException();
    return splitted;
}

try {
    customSplit("004-034556", "-");
}
catch(SplitException se) {
    se.printStackTrace();
}