Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split String for a digit and letters in java

Tags:

java

string

split

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?

like image 652
degath Avatar asked Jun 14 '26 00:06

degath


2 Answers

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"]
like image 90
Bentaye Avatar answered Jun 16 '26 13:06

Bentaye


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()));
like image 30
Santosh Thapa Avatar answered Jun 16 '26 15:06

Santosh Thapa