Java – How to split a string
2015-09-29 09:45
405 查看
To split a string, uses
Output
Note
This
Output
Some common checking before split.
2.
In the old days, Java developers like to use the
Output
Note
This
String.split(regex). Review the following examples :
String phone = "012-3456789"; String[] output = phone.split("-"); System.out.println(output[0]); System.out.println(output[1]);
Output
012 3456789
Note
This
split (regex)takes a regex as an argument, remember to escape the regex special characters, like period/dot.
1. Split a Period / dot
The period / dot is a special character in regex, you have to escape it either with a double backlash\\. or uses the
Pattern.quotemethod.
TestSplit.java
package com.mkyong.test import java.util.regex.Pattern; public class TestSplit { public static void main(String[] args) { String test = "abc.def.123"; String[] output = test.split("\\."); //alternative //String[] output = test.split(Pattern.quote(".")); System.out.println(output[0]); System.out.println(output[1]); System.out.println(output[2]); } }
Output
abc def 123
Some common checking before split.
TestSplit.java
package com.mkyong.test import java.util.regex.Pattern; public class TestSplit { public static void main(String[] args) { String test = "abc.def.123"; if(test.contains(".")){ String[] output = test.split("\\."); if(output.length!=3){ throw new IllegalArgumentException(test + " - invalid format!"); }else{ System.out.println(output[0]); System.out.println(output[1]); System.out.println(output[2]); } }else{ throw new IllegalArgumentException(test + " - invalid format!"); } } }
2. StringTokenizer
example
In the old days, Java developers like to use the StringTokenizerclass to split a string. This is because the
StringTokenizerclass is available since JDK 1.0 and the
String.split()is available since JDK 1.4
TestSplit.java
package com.mkyong.test import java.util.StringTokenizer; public class TestSplit { public static void main(String[] args) { String test = "abc.def.123"; StringTokenizer token = new StringTokenizer(test, "."); while (token.hasMoreTokens()) { System.out.println(token.nextToken()); } } }
Output
abc def 123
Note
This
StringTokenizeris a legacy class, retained for compatibility reasons, the use is discouraged! Please use
string.split().
相关文章推荐
- java反射访问私有成员变量
- java数组初始化及内存分析
- Java数据类型和MySql数据类型对应表
- 举例讲解Java中的多线程编程
- dos命令配置jdk环境
- java数字字符串压缩
- Eclipse中注释部分的签名
- 各种排序算法的分析及java实现
- 【Eclipse】利用本地历史记录回档
- java使用poi处理excel防止数字变成科学计数法的形式
- java 读取数据库图片地址,将图片展示在jsp页面(图片必须在服务器硬盘上,此方法才可成功)
- java使用poi处理excel防止数字变成科学计数法的形式
- Java 字符的验证
- 八大排序算法 java实现
- Java深入---百万数据提取最大的前一百个数据
- ACM中Java的使用
- Java 7 中 NIO.2 的使用——第四节 文件和目录
- 事务基础知识-->Spring事务管理
- 线程本地变更ThreadLocal-->Spring事务管理
- 注解-->Spring配置