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
5
  • Have a look at the split(String, int) method in the String class. Commented Jul 19, 2017 at 13:56
  • @Thomas For my case ,it divides the string into 2 parts String 1="This" ,String2="is my First Line" Commented Jul 19, 2017 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(). Commented Jul 19, 2017 at 14:04
  • see stackoverflow.com/questions/3976616/… Commented Jul 19, 2017 at 14:16
  • Possible duplicate of How to find nth occurrence of character in a string? Commented Jul 19, 2017 at 14:16

5 Answers 5

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");
Sign up to request clarification or add additional context in comments.

1 Comment

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 :)
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]+" "

4 Comments

we need to covert into Array and then append it ,is there any simpler way .Because my string may be like this "This is my hello world " with multiple spaces so i needed to preserve those spaces
Use trim() to avoid spaces at start and end. If there are more space in between use split("\\s*")
my comment didn't convey my problem,now i modified my question.Please have a look
delimiters will be retained.Assign to a new variable
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());

Comments

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

Comments

-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

1 Comment

Why are you spamming duplicate answers? You've also done this to multiple questions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.