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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With