Sometimes we have to split String to array based on delimiters or some regular expression. For example, reading a CSV file line and parsing them to get all the data to a String array. In this tutorial, we will learn how to convert String to Array in Java program.
【java|如何在Java中将字符串转换为数组】有时我们必须根据定界符或某些正则表达式将String拆分为数组 。 例如,读取CSV文件行并将其解析以将所有数据获取到String数组。 在本教程中,我们将学习如何在Java程序中将String转换为Array。
Java中的字符串到数组 (String to Array in Java) String class split(String regex)
can be used to convert String to array in java.
字符串类split(String regex)
可用于在Java中将String转换为数组。
If you are working with java regular expression, you can also use Pattern class split(String regex)
method.
如果使用Java正则表达式 ,则还可以使用Pattern类split(String regex)
方法。
Let’s see how to convert String to an array with a simple java class example.
让我们看看如何通过一个简单的Java类示例将String转换为数组。
package com.journaldev.util;
import java.util.Arrays;
import java.util.regex.Pattern;
public class StringToArrayExample {/**
* This class shows how to convert String to String Array in Java
* @param args
*/
public static void main(String[] args) {
String line = "My name is Pankaj";
//using String split function
String[] words = line.split(" ");
System.out.println(Arrays.toString(words));
//using java.util.regex Pattern
Pattern pattern = Pattern.compile(" ");
words = pattern.split(line);
System.out.println(Arrays.toString(words));
}
}
The output of the above program is:
上面程序的输出是:
[My, name, is, Pankaj]
[My, name, is, Pankaj]
文章图片
Convert String To Array in Java
用Java将字符串转换为数组
Note that Java provides a legacy class StringTokenizer also but you should not use it because it doesn’t have an option for a regular expression and using it is confusing.
请注意,Java还提供了旧式类**StringTokenizer,**但您不应使用它,因为它没有用于正则表达式的选项,使用它会造成混淆。
We can use Java regular expressions also to split String into String array in java, learn more about java regular expression.
我们还可以使用Java正则表达式在Java中将String拆分为String数组,了解有关Java正则表达式的更多信息。
翻译自: https://www.journaldev.com/776/string-to-array-java
推荐阅读
- 面试|MySQL 出现 The table is full 的解决方法
- java|什么是 Apache Shiro
- java|Mysql环境变量配置
- JAVA|MultipartFile文件上传
- 面试|MySQL之创建表的基本操作
- java项目工具|oss与文件上传组件MultipartFile
- COMP3811 Rasterization
- EECS 50 UCI
- 人生不设限|计算机专业Java毕设怎么做