按字符拆分字符串

6

我有一个案例,其中我正在执行以下操作:

final String[] columns = row.split(delimiter.toString());

其中delimiter是一个字符。

当我需要基于制表符(\t)进行分割时,这个方法很有效。但是,当我想要基于管道符进行分割时,即使传入|作为分隔符,它也不能按预期工作。

我读了几篇关于|是一种特殊字符的文章,意思是空或空白,因此它在遇到每个字符时都会进行划分,但是,我不希望出现这种情况。

我可以在代码中对这个管道符号进行简单的检查来解决这个问题:

if ("|".equals(delimiter.toString())) {
    columns = row.split("\\" + delimiter.toString());
}
else {
    columns = row.split(delimiter.toString());
} 

但我不知道是否有更简单的方法来解决这个问题。另外,是否还有其他像|一样的特殊字符需要考虑?

2个回答

18

4
  1. You can use StringUtils from Apache Commons Lang which is equipped with methods accepting plain text, not regular expressions:

    public static String[] split(String str, char separatorChar)
    public static String[] split(String str, String separatorChars)
    
  2. You can also use the StringTokenzier class, which does not expect a regular expression as the delimiter.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接