[java] String.split()用法

Posted in :

在java,可以使用String.split(delimiter),將字串分割成數個token,得到一個回傳的String array。
例如:
String str = "aaa:bbb:ccc:ddd";
String[] tokens = str.split(":");
for (String token:tokens) {
System.out.println(token);
}

結果顯示:
aaa
bbb
ccc
ddd


如果字串中有多個分隔符號時,就須加上”|”。
String str = "aaa:bbb-ccc_ddd";
String[] tokens = str.split(":|-|_");
for (String token:tokens) {
System.out.println(token);
}

結果顯示:
aaa
bbb
ccc
ddd


當delimiter用到特殊字元時,如”.”, “|”, “$”,此時要在特殊字元前面加上”\\”,才會得到正確的結果。
String str = "aaa-bbb-ccc.ddd";
String[] tokens = str.split("-|\\.");
for (String token:tokens) {
System.out.println(token);
}

結果顯示:
aaa
bbb
ccc
ddd


https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java

Just use the appropriate method: String#split().

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Note that this takes a regular expression, so remember to escape special characters if necessary.

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called “metacharacters”.

So, if you want to split on e.g. period/dot . which means “any character” in regex, use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

String[] parts = string.split(Pattern.quote(".")); // Split on period.

To test beforehand if the string contains certain character(s), just use String#contains().

if (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}

Note, this does not take a regular expression. For that, use String#matches() instead.

If you’d like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

If you’d like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42

 


Java 字串操作:
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2,3);
     String d = cde.substring(1, 2);

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., charvalues).

Since:
JDK1.0

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *