我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:
part1 = "004";
part2 = "034556";
这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。
我还想检查字符串中是否有“-”。
我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:
part1 = "004";
part2 = "034556";
这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。
我还想检查字符串中是否有“-”。
当前回答
总结一下:在Java中至少有五种拆分字符串的方法:
String.split():String[]parts=“10,20”.split(“,”);Pattern.compile(regexp).splitAsStream(输入):List<String>strings=Pattern.compile(“\\|”).splitAsStream(“010 | 020202”).collector(Collectors.toList());StringTokenizer(遗留类):StringTokenizer strings=新StringTokeniizer(“欢迎使用EXPLAINJAVA.COM!”,“.”);while(strings.hasMoreTokens()){String substring=strings.nexToken();System.out.println(子字符串);}谷歌瓜瓦拆分器:Iterable<String>result=Splitter.on(“,”).split(“1,2,3,4”);Apache Commons StringUtils:String[]strings=StringUtils.split(“1,2,3,4”,“,”);
因此,您可以根据需要选择最佳选项,例如返回类型(数组、列表或可迭代)。
这里是这些方法的大概述和最常见的示例(如何按点、斜线、问号等分割)
其他回答
消耗最少资源的最快方式可能是:
String s = "abc-def";
int p = s.indexOf('-');
if (p >= 0) {
String left = s.substring(0, p);
String right = s.substring(p + 1);
} else {
// s does not contain '-'
}
我查看了所有答案,发现所有答案都是第三方许可或基于正则表达式的。
下面是我使用的一个很好的哑实现:
/**
* Separates a string into pieces using
* case-sensitive-non-regex-char-separators.
* <p>
* <code>separate("12-34", '-') = "12", "34"</code><br>
* <code>separate("a-b-", '-') = "a", "b", ""</code>
* <p>
* When the separator is the first character in the string, the first result is
* an empty string. When the separator is the last character in the string the
* last element will be an empty string. One separator after another in the
* string will create an empty.
* <p>
* If no separators are set the source is returned.
* <p>
* This method is very fast, but it does not focus on memory-efficiency. The memory
* consumption is approximately double the size of the string. This method is
* thread-safe but not synchronized.
*
* @param source The string to split, never <code>null</code>.
* @param separator The character to use as splitting.
* @return The mutable array of pieces.
* @throws NullPointerException When the source or separators are <code>null</code>.
*/
public final static String[] separate(String source, char... separator) throws NullPointerException {
String[] resultArray = {};
boolean multiSeparators = separator.length > 1;
if (!multiSeparators) {
if (separator.length == 0) {
return new String[] { source };
}
}
int charIndex = source.length();
int lastSeparator = source.length();
while (charIndex-- > -1) {
if (charIndex < 0 || (multiSeparators ? Arrays.binarySearch(separator, source.charAt(charIndex)) >= 0 : source.charAt(charIndex) == separator[0])) {
String piece = source.substring(charIndex + 1, lastSeparator);
lastSeparator = charIndex;
String[] tmp = new String[resultArray.length + 1];
System.arraycopy(resultArray, 0, tmp, 1, resultArray.length);
tmp[0] = piece;
resultArray = tmp;
}
}
return resultArray;
}
使用流拆分并打印字符串
String input = "004-034556";
Stream<String> stream = Arrays.stream(input.split( "-" ));
stream.forEach(System.out::println);
如果要验证字母数字,请将正则表达式更改为[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");
}
}
有时,如果您想拆分包含+的字符串,那么它不会拆分;相反,您将得到一个运行时错误。在这种情况下,首先将+替换为_,然后拆分:
this.text=text.replace("/", "_");
String temp[]=text.split("_");