java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

java拆分字符串split

经常需要用java拆分字符串如1,2,3,4 tom,jim,andy,han

package com.java.lang;

public class StringSp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		java.lang.String a = "my name is yuexiaosheng my blog is java-er.com";

		// java.lang.String 的字符串拆分算法
		String[] arr = a.split(" ");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(i + " " + arr[i]);
		}
		String b = "green|red|blue|black";
		// java.lang.String 的字符串拆分算法
		arr = b.split("|");
		System.out.println("拆分暗礁-------------------------------------------");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(i + " " + arr[i]);
		}
		System.out.println("拆分暗礁-------------------------------------------");
		arr = b.split("\\|");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(i + " " + arr[i]);
		}
	}

}

0 my
1 name
2 is
3 yuexiaosheng
4 my
5 blog
6 is
7 java-er.com
拆分暗礁-------------------------------------------
0
1 g
2 r
3 e
4 e
5 n
6 |
7 r
8 e
9 d
10 |
11 b
12 l
13 u
14 e
15 |
16 b
17 l
18 a
19 c
20 k
拆分暗礁-------------------------------------------
0 green
1 red
2 blue
3 black

结论部分字符串需要转义,否则按空计算 会把字符一个个拆开。


This entry was posted in JAVA and tagged , , , , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-split-string/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply