【问题标题】:Splitting String based on nth Occurence of a String in Java基于Java中字符串的第n次出现拆分字符串
【发布时间】:2017-12-24 20:28:30
【问题描述】:

如何根据分隔符的第 n(例如:第二)次出现来拆分字符串。而除了第 n 次出现之外,应保留所有其他分隔符

I/P:

 String name="This is my First Line";
 int delimiter=" ";
 int count=3;//This is a dynamic value

O/P:

String firstpart=This is my
String Secondpart=First Line

【问题讨论】:

  • 看看String类中的split(String, int)方法。
  • @Thomas 对于我来说,它将字符串分成两部分 String 1="This" ,String2="is my First Line"
  • 啊,现在我明白你的问题了。您想在第三个空间拆分。在这种情况下,动态构建正则表达式。有很多关于表达式应该是什么样子的例子。或者使用indexOf()substring() 的组合。

标签: java regex string


【解决方案1】:

由于正则表达式的限制,您不能将其拆分为 1 行代码,但您可以将其拆分为 2 行:

String firstPart = name.replaceAll("^((.*?" + delimiter + "){" + count + "}).*", "$1");
String secondPart = name.replaceAll("^(.*?" + delimiter + "){" + count + "}(.*)", "$2");

【讨论】:

  • 很好的解决方案,如果字符串包含点,例如This.is.my.First.Line,使用Pattern.quote(delimiter)会更好:)
【解决方案2】:

我是这样理解的

String name="This is my First Line";

 int count=3;

 String s1,s2;

 String arr[]=name.split();//default will be space

 for(i=0;i<arr.length;i++)

   if(i<count)

    s1=s1+arr[i]+" "

   else 

    s2=s2+arr[i]+" "

【讨论】:

  • 我们需要转换成数组然后追加它,有没有更简单的方法。因为我的字符串可能是这样的“这是我的你好世界”,有多个空格,所以我需要保留这些空格
  • 使用 trim() 避免开头和结尾出现空格。如果中间有更多空间使用 split("\\s*")
  • 我的评论没有表达我的问题,现在我修改了我的问题。请看一下
  • 将保留分隔符。分配给新变量
【解决方案3】:

只需使用indexOf 搜索分隔符并重复此操作,直到找到它count次。这是一个sn-p:

String name = "This is my First Line";
String delimiter = " ";
int count = 3;

// Repeativly search for the delimiter
int lastIndex = -1;
for (int i = 0; i < count; i++) {
    // Begin to search from the position after the last matching index
    lastIndex = name.indexOf(delimiter, lastIndex + 1);

    // Could not be found
    if (lastIndex == -1) {
        break;
    }
}

// Get the result
if (lastIndex == -1) {
    System.out.println("Not found!");
} else {
    // Use the index to split
    String before = name.substring(0, lastIndex);
    String after = name.substring(lastIndex);

    // Print the results
    System.out.println(before);
    System.out.println(after);
}

现在会输出

This is my
 First Line

注意最后一行开头的空格(分隔符),如果需要,可以在末尾使用以下代码省略它

// Remove the delimiter from the beginning of 'after'
String after = ...
after = after.subString(delimiter.length());

【讨论】:

    【解决方案4】:
    static class FindNthOccurrence
    {
        String delimiter;
    
        public FindNthOccurrence(String del)
        {
            this.delimiter = del;
        }
    
        public int findAfter(String findIn, int findOccurence)
        {
            int findIndex = 0;
            for (int i = 0; i < findOccurence; i++)
            {
                findIndex = findIn.indexOf(delimiter, findIndex);
                if (findIndex == -1)
                {
                    return -1;
                }
            }
            return findIndex;
        }
    }
    
    FindNthOccurrence nth = new FindNthOccurrence(" ");
    String string = "This is my First Line";
    int index = nth.nthOccurrence(string, 2);
    String firstPart = string.substring(0, index);
    String secondPart = string.substring(index+1);
    

    【讨论】:

      【解决方案5】:

      就这样, 在 Java 8 中测试并完美运行

      public String[] split(String input,int at){
          String[] out = new String[2];
          String p = String.format("((?:[^/]*/){%s}[^/]*)/(.*)",at);
          Pattern pat = Pattern.compile(p);
          Matcher matcher = pat.matcher(input);
             if (matcher.matches()) {
                out[0] = matcher.group(1);// left
                out[1] = matcher.group(2);// right
             }
          return out;
      } 
      
      //Ex: D:/folder1/folder2/folder3/file1.txt
      //if at = 2, group(1) = D:/folder1/folder2  and group(2) = folder3/file1.txt
      

      【讨论】:

      • 你为什么要发送重复的答案?您还对多个问题进行了此操作。
      猜你喜欢
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 2013-06-08
      • 2021-04-07
      • 1970-01-01
      • 2014-10-12
      • 2021-01-29
      相关资源
      最近更新 更多