2

How to Split a String based on the nth(Ex: second) occurence of a delimiter.whereas other than the nth occurence ,all other delimiters should be retained

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
Vijay Manohar
  • 473
  • 1
  • 7
  • 22
  • Have a look at the `split(String, int)` method in the `String` class. – Thomas Jul 19 '17 at 13:56
  • @Thomas For my case ,it divides the string into 2 parts String 1="This" ,String2="is my First Line" – Vijay Manohar Jul 19 '17 at 14:00
  • Ah, now I understand your problem. You want to split on the 3rd space. In that case build a regular expression dynamically. There are lots of examples on how the expression should look like. Alternatively use a combination of `indexOf()` and `substring()`. – Thomas Jul 19 '17 at 14:04
  • see https://stackoverflow.com/questions/3976616/how-to-find-nth-occurrence-of-character-in-a-string – Andreas Jul 19 '17 at 14:16
  • Possible duplicate of [How to find nth occurrence of character in a string?](https://stackoverflow.com/questions/3976616/how-to-find-nth-occurrence-of-character-in-a-string) – Andreas Jul 19 '17 at 14:16
  • @VijayManohar If an user answered your question please also **accept** his answer ([Accepting Answers: How does it work?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)). If not than please specify what remains unanswered, this is a really crucial part of StackOverflow, thank you very much. – Zabuzard Jul 27 '17 at 11:47

5 Answers5

5

Due to limitations with regex, you can't split it in 1 line of code, but you can do it in 2 lines:

String firstPart = name.replaceAll("^((.*?" + delimiter + "){" + count + "}).*", "$1");
String secondPart = name.replaceAll("^(.*?" + delimiter + "){" + count + "}(.*)", "$2");
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • good solution, it can be better if you use `Pattern.quote(delimiter)` in case of string contains dot for example `This.is.my.First.Line` :) – Youcef LAIDANI Jul 19 '17 at 14:55
1

I got it like this

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]+" "
1

Just use indexOf to search for the delimiter and repeat that until you found it count-times. Here is a snippet:

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);
}

It will now output

This is my
 First Line

Note the whitespace (the delimiter) at the beginning of the last line, you can omit this if you want by using the following code at the end

// Remove the delimiter from the beginning of 'after'
String after = ...
after = after.subString(delimiter.length());
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
0
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);
daniu
  • 14,137
  • 4
  • 32
  • 53
-1

Simply like this, Tested and work perfectly in 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