本文介绍了如何防止java.lang.String.split()创建前导空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将0用作限制参数可以防止尾随空字符串,但是如何防止前导空字符串?

passing 0 as a limit argument prevents trailing empty strings, but how does one prevent leading empty strings?

例如

String[] test = "/Test/Stuff".split("/");

结果为包含",测试",填充"的数组.

results in an array with "", "Test", "Stuff".

是的,我知道我可以使用自己的令牌生成器...但是StringTokenizer的API文档说

Yeah, I know I could roll my own Tokenizer... but the API docs for StringTokenizer say

推荐答案

您最好的选择可能就是删除任何领先的分隔符:

Your best bet is probably just to strip out any leading delimiter:

String input = "/Test/Stuff";
String[] test = input.replaceFirst("^/", "").split("/");

您可以通过以下方法使其更通用:

You can make it more generic by putting it in a method:

public String[] mySplit(final String input, final String delim)
{
    return input.replaceFirst("^" + delim, "").split(delim);
}

String[] test = mySplit("/Test/Stuff", "/");

这篇关于如何防止java.lang.String.split()创建前导空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:32