Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find before and after sub-string in a string

Tags:

I have a string say 123dance456 which I need to split into two strings containing the first sub-string before the sub-string dance (i.e. 123) and after the sub-string dance (i.e. 456). I need to find them and hold them in separate string variables, say String firstSubString = 123; and String secondSubString = 456;.

Is there any given String method that does just that?

like image 209
skip Avatar asked Jan 15 '12 17:01

skip


People also ask

How do you find before and after substring in a string?

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 find the sub string of a string?

To locate a substring in a string, use the indexOf() method. Let's say the following is our string. String str = "testdemo"; Find a substring 'demo' in a string and get the index.

How do I get substring after?

We want the substring after the first occurrence of the separator i.e. For that, first you need to get the index of the separator and then using the substring() method get, the substring after the separator. String separator ="-"; int sepPos = str. indexOf(separator); System.


1 Answers

You can use String.split(String regex). Just do something like this:

String s = "123dance456"; String[] split = s.split("dance"); String firstSubString = split[0]; String secondSubString = split[1]; 

Please note that if "dance" occurs more than once in the original string, split() will split on each occurrence -- that's why the return value is an array.

like image 82
Alex D Avatar answered Nov 02 '22 12:11

Alex D