【问题标题】:How to split a string into an array of suffixes?如何将字符串拆分为后缀数组?
【发布时间】:2013-02-12 02:40:21
【问题描述】:

将字符串拆分为其后缀数组的最有效方法是什么?

假设你有字符串“天气很好”,我想生成一个这样的后缀数组:

[0] = "nice"

[1] = "is nice"

[2] = "weather is nice"

[3] = "the weather is nice"

我可以通过迭代器的形式从头到尾访问其标记(单词)的字符串。

【问题讨论】:

  • 必须是数组吗?我会推荐一个Iterable<String>,如果你愿意,可以告诉你如何

标签: java arrays search phrase


【解决方案1】:

使用split 在空格上拆分数组,然后从后到前遍历生成的标记,取前一个后缀,并将当前标记放在其前面。如果没有前置后缀,则使用空字符串:

String str = "quick brown fox jumps over the lazy dog";
List<String> res = new ArrayList<String>();
String last = null;
String[] tok = str.split(" ");
for (int i = tok.length-1 ; i >= 0 ; i--) {
    if (last == null) {
        last = tok[i];
    } else {
        last = tok[i] + " " + last;
    }
    res.add(last);
}
for (String s : res) {
    System.out.println(s);
}

打印出来

dog
lazy dog
the lazy dog
over the lazy dog
jumps over the lazy dog
fox jumps over the lazy dog
brown fox jumps over the lazy dog
quick brown fox jumps over the lazy dog

Link to a demo on ideone.

【讨论】:

    【解决方案2】:

    调用 .split(" ");将返回字符串中的单词数组。

    javadoc

    【讨论】:

      【解决方案3】:

      显而易见的解决方案是在空格上标记字符串并将结果以相反的顺序存储在ListArray&lt;String&gt; 中。然后从中构建你的答案ListArray,一点递归对灵魂有好处..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-18
        • 1970-01-01
        • 2016-04-01
        • 2012-02-22
        相关资源
        最近更新 更多