+1 vote
1 view
in Java by (830 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 (13.2k points)

There is a method in Java that can help you achieve your goal.The string.split() method divides a given string in two parts around a given regular expression.The syntax of the function is -

public String[] split(String regex)

Here,  regex - a regular expression

This method returns an array of strings computed by splitting the given string.

Now, first you want to check if the string contains a particular character or not, to do this use string.contains()

So, your final code becomes,

String string = "004-034556";

if (string.contains("-")) {

    // Split it.

String[] stringParts = string.split("-");

String partOne = parts[0]; // 004-

String partTwo = parts[1]; // 034556

} else {

    throw new IllegalArgumentException("String " + string + " does not contain -");

}

...