简体   繁体   English

拆分字符串由一个artbitrary字符分隔

[英]Split Strings separated by an artbitrary character

Say we would like to write a method to receive entire book in a string and an arbitrary single-character delimiter to separate strings and return an array of strings. 假设我们想编写一个方法来接收字符串中的整本书和一个任意的单字符分隔符来分隔字符串并返回一个字符串数组。 I came up with the following implementation (Java).(suppose no consecutive delimiter etc) 我提出了以下实现(Java)。(假设没有连续的分隔符等)

ArrayList<String> separater(String book, char delimiter){
ArrayList<String> ret = new ArrayList<>();
String word ="";

    for (int i=0; i<book.length(), ++i){
        if (book.charAt(i)!= delimiter){
            word += book.charAt(i);
        } else {
            ret.add(word);
            word = "";
        }
    }
    return ret;
}

Question: I wonder if there is any way to leverage String.split() for shorter solutions? 问:我想知道是否有任何方法可以利用String.split()获得更短的解决方案? Its because I could not find a general way of defining a general regex for an arbitrary character delimiter. 因为我找不到为任意字符分隔符定义一般正则表达式的一般方法。

String.split("\\.") if the delimiter is '.'
String.split("\\s+"); if the delimiter is ' ' // space character 

That measn I cold not find a general way of generating the input regex of method split() from the input character delimiter. 那个测量我很冷,没有找到从输入字符分隔符生成方法split()的输入正则表达式的一般方法。 Any suggestions? 有什么建议么?

String[] array = string.split(Pattern.quote(String.valueOf(delimiter)));

That said, The Guava Splitter is much more versatile and well-behaving than String.split() . 也就是说,Guava Splitter比String.split()更通用,性能更好。

And a note on your method: concatenating to a String in a loop is very inefficient. 并且关于您的方法的注释:在循环中连接到String是非常低效的。 As Strings are immutable, it produces a lot of temporary Strings and StringBuilders. 由于字符串是不可变的,它会产生许多临时字符串和StringBuilders。 You should use a StringBuilder instead. 您应该使用StringBuilder。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM