如何在Java中拆分字符串

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

string1="004";string2="034556";

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

如何在Java中拆分字符串

BIG阳
浏览 4076回答 4
4回答

手掌心

// 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&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;public static String[] SplitUsingTokenizer(String subject, String delimiters) {&nbsp; &nbsp;StringTokenizer strTkn = new StringTokenizer(subject, delimiters);&nbsp; &nbsp;ArrayList<String> arrLis = new ArrayList<String>(subject.length());&nbsp; &nbsp;while(strTkn.hasMoreTokens())&nbsp; &nbsp; &nbsp; arrLis.add(strTkn.nextToken());&nbsp; &nbsp;return arrLis.toArray(new String[0]);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java