Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (4k points)

I have a string, "004-034556", that I want to split into two strings:

string1="004";

string2="034556";

That means the first string will contain the characters before '-', and the second string will contain the characters after '-'. I also want to check if the string has '-' in it. If not, I will throw an exception. How can I do this?

1 Answer

0 votes
by (46k points)

Try:

String[] result = yourString.split("-");

if (result.length != 2) 

     throw new IllegalArgumentException("String not in correct format");

This will split your string into 2 parts. The first element in the array will be the part containing the stuff before the -, and the 2nd element in the array will contain the part of your string after the -.

If the array length is not 2, then the string was not in the format: string-string.

Check out the split() method in the String class.

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-int-

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...