Splitting strings in Java

Asked 2 years ago, Updated 2 years ago, 116 views

There is a string called "004-034556", separated by '-'

string1=004;
string2=034556;

I want to split it like this. So I want to find '-' and make an exception if there is none, what should I do?

string java

2022-09-22 22:35

1 Answers

String has a method called split().

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

In the example above, you can use it this way.

If you make an exception,

if (string.contains("-")) {
    String string = "004-034556";
    String[] parts = string.split("-");
    String part1 = parts[0]; // 004
    String part2 = parts[1]; // 034556
} } else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}

You can do it.


2022-09-22 22:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.