如何在Java中拆分一个字符串
时间:2020-02-23 14:34:23 来源:igfitidea点击:
在本教程中,我们将看到如何在Java中通过分隔符分隔字符串。
有时,我们需要通过分隔符拆分字符串:在读取CSV文件时,我们需要通过逗号(,)拆分字符串。
我们将使用String类的拆分方法拆分字符串。
此拆分(正则表达式)将正则表达式作为参数拍摄,因此我们需要转义某些正则表达式特殊字符,例如点(。
)。
拆分方法返回一系列字符串。
例子:
package org.igi.theitroad;
public class StringSplitMain {
public static void main(String args[])
{
//Splitting String separated by comma
System.out.println("--------------------");
System.out.println("Splitting by comma");
System.out.println("--------------------");
String str= "Netherlands,Delhi,200400";
String[] strArr=str.split(",");
for (int i = 0; i < strArr.length; i++) {
System.out.println(strArr[i]);
}
//Splitting String by dot(.)
//We need to put escape character in case of . as it is regex special character
System.out.println("--------------------");
System.out.println("Splitting by Dot");
System.out.println("--------------------");
String strDot= "Netherlands.Delhi.200400";
String[] strArrDot=strDot.split("\.");
for (int i = 0; i < strArrDot.length; i++) {
System.out.println(strArrDot[i]);
}
}
}
运行上面的程序时,我们将获取以下输出:
------------------- Splitting by comma ------------------- Netherlands Delhi 200400 ------------------- Splitting by Dot ------------------- Netherlands Delhi 200400

