【问题标题】:Java, How to split String with shiftingJava,如何通过移位拆分字符串
【发布时间】:2013-08-02 16:21:36
【问题描述】:

我如何用2 字符和shifting 分割字符串。 例如;

我的字符串是 = todayiscold

我的目标是:"to","od","da","ay","yi","is","sc","co","ol","ld"

但使用此代码:

Arrays.toString("todayiscold".split("(?<=\\G.{2})")));

我得到:`"to","da","yi","co","ld"

有人帮忙吗?

【问题讨论】:

  • String.split 将在特定点拆分。根据定义,这些字符串不能重叠。

标签: java regex string split


【解决方案1】:

试试这个:

        String e = "example";
        for (int i = 0; i < e.length() - 1; i++) {
            System.out.println(e.substring(i, i+2));
        }

【讨论】:

  • @Jason 我同意但有效的解决方案通常更复杂,在这里我提出简单易懂的解决方案。这个问题根本与性能无关。
  • 不,我不同意。你应该考虑它确实计量的性能。 “过早的优化是编程中万恶(或至少是大部分)的根源”(Donald Knuth
  • 编程史上被误解的第二名。
  • “这个解决方案抓取每个字符 n 次” - 不正确,这实际上根本没有抓取任何字符。当使用substring 时,支持Stringchar[] 在它和创建的新String 之间共享。新的String 只是使用不同的开始和结束位置,因此实际上根本不会复制任何字符。
  • @Syon 实际上这也不完全正确 :) 它是在 changed implementation。
【解决方案2】:

使用循环:

String test = "abcdefgh";
List<String> list = new ArrayList<String>();
for(int i = 0; i < test.length() - 1; i++)
{
   list.add(test.substring(i, i + 2));
}

【讨论】:

    【解决方案3】:

    以下基于正则表达式的代码应该可以工作:

    String str = "todayiscold";
    Pattern p = Pattern.compile("(?<=\\G..)");
    Matcher m = p.matcher(str);
    int start = 0;
    List<String> matches = new ArrayList<String>();
    while (m.find(start)) {
        matches.add(str.substring(m.end()-2, m.end()));
        start = m.end()-1;
    }
    System.out.println("Matches => " + matches);
    

    诀窍是在 find() 方法中使用上次匹配的 end()-1

    输出:

    Matches => [to, od, da, ay, yi, is, sc, co, ol, ld]
    

    【讨论】:

      【解决方案4】:

      在这种情况下你不能使用split,因为所有的分割都是在这个地方找到分割和制动你的字符串的地方,所以你不能让相同的字符出现在两个部分中。

      相反,您可以使用模式/匹配器机制,例如

      String test = "todayiscold";
      List<String> list = new ArrayList<String>();
      
      Pattern p = Pattern.compile("(?=(..))");
      Matcher m = p.matcher(test);
      while(m.find())
          list.add(m.group(1));
      

      甚至更好地迭代您的 Atring 字符并创建子字符串,例如 D-Rock 的 answer

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-22
        • 1970-01-01
        • 2013-03-03
        • 1970-01-01
        • 2016-04-28
        • 2018-12-22
        • 1970-01-01
        相关资源
        最近更新 更多