我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:

part1 = "004";
part2 = "034556";

这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。

我还想检查字符串中是否有“-”。


当前回答

使用Regex使用多个字符拆分字符串

public class StringSplitTest {
     public static void main(String args[]) {
        String s = " ;String; String; String; String, String; String;;String;String; String; String; ;String;String;String;String";
        //String[] strs = s.split("[,\\s\\;]");
        String[] strs = s.split("[,\\;]");
        System.out.println("Substrings length:"+strs.length);
        for (int i=0; i < strs.length; i++) {
            System.out.println("Str["+i+"]:"+strs[i]);
        }
     }
  }

输出:

Substrings length:17
Str[0]:
Str[1]:String
Str[2]: String
Str[3]: String
Str[4]: String
Str[5]: String
Str[6]: String
Str[7]:
Str[8]:String
Str[9]:String
Str[10]: String
Str[11]: String
Str[12]:
Str[13]:String
Str[14]:String
Str[15]:String
Str[16]:String

但不要期望所有JDK版本都有相同的输出。我看到了一个bug,在某些JDK版本中,第一个空字符串被忽略了。此错误在最新的JDK版本中不存在,但在JDK1.7晚期版本和1.8早期版本之间的某些版本中存在。

其他回答

这:

String[] out = string.split("-");

应该做你想做的事。string类有许多方法可用于字符串操作。

有时,如果您想拆分包含+的字符串,那么它不会拆分;相反,您将得到一个运行时错误。在这种情况下,首先将+替换为_,然后拆分:

 this.text=text.replace("/", "_");
            String temp[]=text.split("_");

我查看了所有答案,发现所有答案都是第三方许可或基于正则表达式的。

下面是我使用的一个很好的哑实现:

/**
 * Separates a string into pieces using
 * case-sensitive-non-regex-char-separators.
 * <p>
 * &nbsp;&nbsp;<code>separate("12-34", '-') = "12", "34"</code><br>
 * &nbsp;&nbsp;<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;
}
// 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        

public static String[] SplitUsingTokenizer(String subject, String delimiters) {
   StringTokenizer strTkn = new StringTokenizer(subject, delimiters);
   ArrayList<String> arrLis = new ArrayList<String>(subject.length());

   while(strTkn.hasMoreTokens())
      arrLis.add(strTkn.nextToken());

   return arrLis.toArray(new String[0]);
}

要拆分字符串,请使用string.split(regex)。查看以下示例:

String data = "004-034556";
String[] output = data.split("-");
System.out.println(output[0]);
System.out.println(output[1]);

输出

004
034556

注:

此拆分(正则表达式)以正则表达式作为参数。记住转义正则表达式特殊字符,如句点/点。