Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substring before nth occurence of a separator?

Tags:

java

string

split

first;snd;3rd;4th;5th;6th;...

How can I split the above after the third occurence of the ; separator? Especially without having to value.split(";") the whole string as an array, as I won't need the values separated. Just the first part of the string up until nth occurence.

Desired output would be: first;snd;3rd. I just need that as a string substring, not as split separated values.

like image 943
membersound Avatar asked Dec 13 '18 15:12

membersound


People also ask

How do you get a string before a specific substring?

Use the substring() method to get the substring before a specific character, e.g. const before = str. substring(0, str. indexOf('_')); . The substring method will return a new string containing the part of the string before the specified character.

How do you split a string with every nth character?

To split a string every n characters: Import the wrap() method from the textwrap module. Pass the string and the max width of each slice to the method. The wrap() method will split the string into a list with items of max length N.

How do you get the part of a string before a specific character in Java?

Using indexOf and substring Another, more manual way to do this is to use the indexOf() method to get the index of the character you want to extract. With this index, you can then use the substring() method to get the substring before that index.


1 Answers

Use StringUtils.ordinalIndexOf() from Apache

Finds the n-th index within a String, handling null. This method uses String.indexOf(String).

Parameters:

str - the String to check, may be null

searchStr - the String to find, may be null

ordinal - the n-th searchStr to find

Returns: the n-th index of the search String, -1 (INDEX_NOT_FOUND) if no match or null string input

Or this way, no libraries required:

public static int ordinalIndexOf(String str, String substr, int n) {
    int pos = str.indexOf(substr);
    while (--n > 0 && pos != -1)
        pos = str.indexOf(substr, pos + 1);
    return pos;
}
like image 168
Akceptor Avatar answered Sep 18 '22 01:09

Akceptor