我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:
part1 = "004";
part2 = "034556";
这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。
我还想检查字符串中是否有“-”。
我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:
part1 = "004";
part2 = "034556";
这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。
我还想检查字符串中是否有“-”。
当前回答
public class SplitTest {
public static String[] split(String text, String delimiter) {
java.util.List<String> parts = new java.util.ArrayList<String>();
text += delimiter;
for (int i = text.indexOf(delimiter), j=0; i != -1;) {
String temp = text.substring(j,i);
if(temp.trim().length() != 0) {
parts.add(temp);
}
j = i + delimiter.length();
i = text.indexOf(delimiter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str = "004-034556";
String delimiter = "-";
String result[] = split(str, delimiter);
for(String s:result)
System.out.println(s);
}
}
其他回答
你真正需要考虑的方法只有两种。
使用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对象。您还可以缓存此对象并为每个输入重置它以获得最大性能,但这有点复杂,而且不线程安全。
实现这一点的一种方法是在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
对于简单的用例,String.split()应该完成这项工作。如果您使用番石榴,还有一个Splitter类,它允许链接不同的字符串操作并支持CharMatcher:
Splitter.on('-')
.trimResults()
.omitEmptyStrings()
.split(string);
我查看了所有答案,发现所有答案都是第三方许可或基于正则表达式的。
下面是我使用的一个很好的哑实现:
/**
* 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;
}
Use:
String[] result = yourString.split("-");
if (result.length != 2)
throw new IllegalArgumentException("String not in correct format");
这将把你的绳子分成两部分。数组中的第一个元素将是包含-之前的内容的部分,数组中的第二个元素将包含-之后的字符串部分。
如果数组长度不是2,则字符串的格式不是:string string。
查看String类中的split()方法。