Skip to content

Commit dff6208

Browse files
committed
how-to-split-a-string-in-java
1 parent 9ae0d7f commit dff6208

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ stackoverflow-Java-top-qa
1818
* [重写(Override)equlas和hashCode方法时应考虑的问题](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java.md)
1919
* [从一个多层嵌套循环中直接跳出](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/breaking-out-of-nested-loops-in-java.md)
2020
* [如何将String转换为Int](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/converting-string-to-int-in-java.md)
21+
* [如何分割(split)string字符串](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/how-to-split-a-string-in-java.md)
2122

2223
> 编程技巧
2324
@@ -109,7 +110,6 @@ stackoverflow-Java-top-qa
109110
- [decompiling DEX into Java sourcecode](http://stackoverflow.com/questions/1249973/decompiling-dex-into-java-sourcecode)
110111
- [How to create a generic array in Java?](http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java)
111112
- [Why does Math.round(0.49999999999999994) return 1](http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1)
112-
- [How to split a string in Java](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java)
113113
- [Eclipse: Set maximum line length for auto formatting?](http://stackoverflow.com/questions/3697287/eclipse-set-maximum-line-length-for-auto-formatting)
114114
- [What is the difference between a soft reference and a weak reference in Java?](http://stackoverflow.com/questions/299659/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java)
115115
- [How to create a file and write to a file in Java?](http://stackoverflow.com/questions/2885173/how-to-create-a-file-and-write-to-a-file-in-java)
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
##如何分割(split)string字符串
2+
使用[`String#split()`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-)方法
3+
4+
如下所示:
5+
```java
6+
String string = "004-034556";
7+
String[] parts = string.split("-");
8+
String part1 = parts[0]; // 004
9+
String part2 = parts[1]; // 034556
10+
```
11+
需要注意的是,该方法的参数是个[正则表达式](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sum),要注意对某些字符做转码。例如,`.`在正则表达式中表示任意字符,因此,如果你要通过`.`号做分割,需要这样写,`split("\\.")`或者`split(Pattern.quote("."))`
12+
13+
如果只是为了验证字符串中是否包含某个字符,使用[`String#contains`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#contains-java.lang.CharSequence-)方法就行。注意该方法的参数,不是正则表达式
14+
15+
stackoverflow链接:
16+
http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java

0 commit comments

Comments
 (0)