我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:
part1 = "004";
part2 = "034556";
这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。
我还想检查字符串中是否有“-”。
我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:
part1 = "004";
part2 = "034556";
这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。
我还想检查字符串中是否有“-”。
当前回答
你真正需要考虑的方法只有两种。
使用String.split作为一个字符分隔符,否则您不关心性能
如果性能不是问题,或者分隔符是不是正则表达式特殊字符的单个字符(即,不是.$|()[{^?*+\之一),则可以使用String.split。
String[] results = input.split(",");
如果delimeter是单个字符而不在上面的列表中,则split方法有一个优化,以避免使用正则表达式。否则,它必须编译正则表达式,这是不理想的。
如果使用复杂的分隔符并且您关心性能,请使用Pattern.split并预编译模式。
如果性能是一个问题,并且分隔符不是上述问题之一,那么应该预先编译一个正则表达式模式,然后可以重用它。
// Save this somewhere
Pattern pattern = Pattern.compile("[,;:]");
/// ... later
String[] results = pattern.split(input);
最后一个选项仍然会创建一个新的Matcher对象。您还可以缓存此对象并为每个输入重置它以获得最大性能,但这有点复杂,而且不线程安全。
其他回答
如果要验证字母数字,请将正则表达式更改为[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");
}
}
使用Java 8:
List<String> stringList = Pattern.compile("-")
.splitAsStream("004-034556")
.collect(Collectors.toList());
stringList.forEach(s -> System.out.println(s));
无论是否有任何类型的分隔符,您都可以简单地使用StringTokenizer将字符串拆分为两个或多个部分:
StringTokenizer st = new StringTokenizer("004-034556", "-");
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
String str="004-034556"
String[] sTemp=str.split("-");// '-' is a delimiter
string1=004 // sTemp[0];
string2=034556//sTemp[1];
您可以使用拆分方法:
public class Demo {
public static void main(String args[]) {
String str = "004-034556";
if ((str.contains("-"))) {
String[] temp = str.split("-");
for (String part:temp) {
System.out.println(part);
}
}
else {
System.out.println(str + " does not contain \"-\".");
}
}
}