我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:
part1 = "004";
part2 = "034556";
这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。
我还想检查字符串中是否有“-”。
我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:
part1 = "004";
part2 = "034556";
这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。
我还想检查字符串中是否有“-”。
当前回答
要拆分字符串,请使用string.split(regex)。查看以下示例:
String data = "004-034556";
String[] output = data.split("-");
System.out.println(output[0]);
System.out.println(output[1]);
输出
004
034556
注:
此拆分(正则表达式)以正则表达式作为参数。记住转义正则表达式特殊字符,如句点/点。
其他回答
实现这一点的一种方法是在for每个循环中运行字符串,并使用所需的拆分字符。
public class StringSplitTest {
public static void main(String[] arg){
String str = "004-034556";
String split[] = str.split("-");
System.out.println("The split parts of the String are");
for(String s:split)
System.out.println(s);
}
}
输出:
The split parts of the String are:
004
034556
无论是否有任何类型的分隔符,您都可以简单地使用StringTokenizer将字符串拆分为两个或多个部分:
StringTokenizer st = new StringTokenizer("004-034556", "-");
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
如果要验证字母数字,请将正则表达式更改为[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.split()应该完成这项工作。如果您使用番石榴,还有一个Splitter类,它允许链接不同的字符串操作并支持CharMatcher:
Splitter.on('-')
.trimResults()
.omitEmptyStrings()
.split(string);
有时,如果您想拆分包含+的字符串,那么它不会拆分;相反,您将得到一个运行时错误。在这种情况下,首先将+替换为_,然后拆分:
this.text=text.replace("/", "_");
String temp[]=text.split("_");