1

我正在尝试将字符串拆分为字符串数组,可能有多种组合,我尝试过:

String strExample = "A, B";
//possible option are:

1. A,B 
2. A, B
3. A , B
4. A ,B

String[] parts;
parts = strExample.split("/"); //Split the string but doesnt remove the space in between them so the 2 item in the string array is space and B ( B)
parts = strExample.split("/| ");
parts = strExample.split(",|\\s+");

任何指导将不胜感激

4

2 回答 2

1

要使用包含可选空格字符的逗号分隔,您可以使用

s.split("\\s*,\\s*")

模式\s*,\s*匹配

  • \s*- 0+ 个空格
  • ,- 一个逗号
  • \s*- 0+ 个空格

如果您想确保没有前导/尾随空格,请考虑trim()在拆分之前对字符串进行 ming。

于 2018-12-18T11:28:22.003 回答
0

您可以使用

parts=strExample.split("\\s,\\s*");

对于你的情况。

于 2018-12-18T11:22:51.543 回答