Test data are e.g.
1a, 12a, 1ab, 12ab, 123a, 123abc
so if as input we have:
String input = "1a";
The output will be
String number = "1";
String letter = "a";
Like you can notice in this String there are sometimes 1-3digits(0-9) and sometimes 1-3letters(A-Z).
My first attempt:
I tried to use .substring()
But it will work only if there would've been for example always the same amount of digits or letters
My second attempt was:
.split(" ");
But it will work only if there will be a space or any other sign between.
PS. Thanks for a response in answers. I checked most of your answers and they all work. The question now which one is the best?
A simple solution without regular expressions: Find the index of the first Letter and split the string at this position.
private String[] splitString(String s) {
// returns an OptionalInt with the value of the index of the first Letter
OptionalInt firstLetterIndex = IntStream.range(0, s.length())
.filter(i -> Character.isLetter(s.charAt(i)))
.findFirst();
// Default if there is no letter, only numbers
String numbers = s;
String letters = "";
// if there are letters, split the string at the first letter
if(firstLetterIndex.isPresent()) {
numbers = s.substring(0, firstLetterIndex.getAsInt());
letters = s.substring(firstLetterIndex.getAsInt());
}
return new String[] {numbers, letters};
}
Gives you:
splitString("123abc")
returns ["123", "abc"]
splitString("123")
returns ["123", ""]
splitString("abc")
returns ["", "abc"]
If your string sequence starts with digits and ends with letters, then the below code will work.
int asciRepresentation, startCharIndex = -1;
for(int i = 0; i < str.length(); i++) {
asciRepresentation = (int) str.charAt(i);
if (asciRepresentation > 47 && asciRepresentation < 58)
strB.append(str.charAt(i));
else {
startCharIndex = i;
break;
}
}
System.out.println(strB.toString());
if (startCharIndex != -1)
System.out.println(str.substring(startCharIndex, str.length()));
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