Java如何以逗号和空格分割字符串
时间: 2024-02-17 22:02:04 浏览: 174
可以使用 String 类的 split 方法来实现以逗号和空格分割字符串。示例代码如下:
```java
String str = "Java is a programming language, and it is used widely.";
String[] words = str.split("[,\\s]+");
for (String word : words) {
System.out.println(word);
}
```
输出结果为:
```
Java
is
a
programming
language
and
it
is
used
widely.
```
在上述代码中,`split("[,\\s]+")`中的`[,]`表示匹配逗号,`[\\s]`表示匹配空格,`+`表示匹配一个或多个逗号或空格。这样就可以将字符串按照逗号和空格分割成一个字符串数组。
相关问题
Java如何以逗号和空格和小于号大于号分割字符串
可以使用正则表达式来实现以逗号、空格、小于号和大于号分割字符串。示例代码如下:
```java
String str = "Java is a <programming> language, and it is used <widely>.";
String[] words = str.split("[,\\s<>]+");
for (String word : words) {
System.out.println(word);
}
```
输出结果为:
```
Java
is
a
programming
language
and
it
is
used
widely.
```
在上述代码中,`split("[,\\s<>]+")`中的`[,]`表示匹配逗号,`[\\s]`表示匹配空格,`[<>]`表示匹配小于号和大于号,`+`表示匹配一个或多个逗号、空格、小于号或大于号。这样就可以将字符串按照逗号、空格、小于号和大于号分割成一个字符串数组。
java如何将数组转为逗号分割的字符串
在 Java 中,可以使用 StringBuilder 类来将数组转换为逗号分隔的字符串。
例如,如果要将整型数组转换为字符串,可以使用以下代码:
```
int[] arr = {1, 2, 3, 4, 5};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]);
if (i < arr.length - 1) {
sb.append(", ");
}
}
String str = sb.toString();
```
输出字符串为:"1, 2, 3, 4, 5"
这里的代码将数组中的每个元素添加到 StringBuilder 对象中,并在每个元素之间添加逗号和空格。最后,调用 StringBuilder 的 toString() 方法将其转换为字符串。
也可以使用 Java 8 中的 Stream API 和 String.join() 方法来实现同样的功能:
```
int[] arr = {1, 2, 3, 4, 5};
String str = String.join(", ", Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new));
```
输出字符串为:"1, 2, 3, 4, 5"
这里的代码将数组转换为 IntStream,然后使用 mapToObj() 方法将每个整数映射为字符串,最后使用 String.join() 将所有字符串连接在一起,使用逗号和空格作为分隔符。
注意:如果数组为空或 null,上述代码将会返回空字符串。
阅读全文
相关推荐














