我正在逐行读取一个文件,并希望根据特定的分隔符拆分每一行。我在 String 类和 StringUtils 类中找到了一些可用的选项。
所以我的问题是哪个是更好的选择,为什么?
最佳答案
这取决于用例。
What's the difference ?
String[] 拆分(String 正则表达式)
String[] results = StringUtils.split(String str,String separatorChars)
Apache utils split() 是 null 安全的。
StringUtils.split(null)
将返回null
。 JDK 默认不是 null 安全的:尝试{ 字符串 testString = null; String[] result = testString.split("-"); System.out.println(result.length); } catch (异常 e){ System.out.println(e);//结果 NPE }
默认String#split()使用正则表达式拆分字符串。
Apache 版本 StringUtils#split()使用 whitespace/char/String characters/null [取决于 split() 方法签名]。
由于复杂的正则表达式在广泛使用时非常昂贵,因此默认的String.split()
将不是一个好主意。否则更好。当用于标记字符串时,如下面的 string.split() 返回一个额外的空字符串。而 Apache 版本给出了 正确结果
String testString = "$Hello$Dear$";
String[] result = testString.split("\\$");
System.out.println("Length is "+ result.length); //3
int i=1;
for(String str : result) {
System.out.println("Str"+(i++)+" "+str);
}
Output
Length is 3 Str1 Str2 Hello Str3 Dear
String[] result = StringUtils.split(testString,"$");
System.out.println("Length is "+ result.length); // 2
int i=1;
for(String str : result) {
System.out.println("Str"+(i++)+" "+str);
}
Output
Length is 2 Str1 Hello Str2 Dear
关于java - String类中的split方法和Apache StringUtils中的split方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25945854/