在while循环中创建子字符串

时间:2017-10-20 02:54:19

标签: java substring

我正在尝试从一个单词(labelA)到另一个单词(labelB)创建一个substrings string的方法,反之亦然。

如果字符串是The Number2 quick Number1 onyx goblin jumps Number1 over the lazy dwarf Number2

我试图将标签之间的字符串分配给Sub变量。

因此,在每次运行while循环时,输出向量将具有与此类似的值

temp.addElement("Number2");
temp.add("The");

然后

temp.addElement("Number1");
temp.add("quick ");

然后

temp.addElement("Number1");
temp.add("onyx goblin jumps  ");

然后

temp.addElement("Number2");
temp.add("over the lazy dwarf  ");

这就是我试过的

 private Vector cutter(String str){
    Vector thisPlan - new Vector();
    Vector temp = new Vector();
    try{
       int i =0;
       int end = 0;
       String labelA = "Number1:";
       String labelB = "Number2:";
       String Sub = "";
       int pos = 0;
       while(i<r.length()){
         try{
             pos = str.indexOf(labelA, pos);
             Sub = str.substring(pos,str.length());
             pos++;
         }catch(Exception e){
             pos = str.indexOf)(labelB, pos);
             Sub = str.substring(pos,str.length());
              pos++;
         }
         if(!labelA.equals(labelB) || (labelA.equals(labelB) && !StringUtil.scrub(Sub).equals(""))){
          temp.addElement(labelA);
          temp.add(Sub);
         }
         if(!labelA.equals(labelB) || (labelA.equals(labelB) && !StringUtil.scrub(Sub).equals(""))){
           temp.addElement(labelB);
           temp.add(Sub);
          }
          temp = new Vector();
      } catch (Exception e){
       }
      return thisPlan;
    }
}

请帮助,至少提出建议我如何才能实现这一目标。

1 个答案:

答案 0 :(得分:1)

String.split(String)我会相信这个诀窍:

"The Number2 quick Number1 onyx goblin jumps Number1 over the lazy dwarf Number2 ")
    .split("Number2|Number1")

等于

["The ", " quick ", " onyx goblin jumps ", " over the lazy dwarf ", " "]

看起来很像我相信你正在寻找的东西。

要同时保留"Number1""Number2"分隔字符串,您可以使用zero-width positive lookahead and lookbehind expressionshttps://stackoverflow.com/a/19951885/1840078中使用的How to split a string, but also keep the delimiters?

"The Number2 quick Number1 onyx goblin jumps Number1 over the lazy dwarf Number2 "
    .split("(?=Number[12])|(?<=Number[12])")

等于

["The ", "Number2", " quick ", "Number1", " onyx goblin jumps ",
    "Number1", " over the lazy dwarf ", "Number2", " "]