Java String Split: Separating Letters and Digits

Splitting a Java String into letters and digits can be a useful operation when dealing with data that contains alphanumeric characters. The String.split() method can be used to achieve this separation.

├Źndice
  1. Using Regular Expressions
  2. Using Character Classes

Using Regular Expressions

One way to split a Java String into letters and digits is to use regular expressions. The regular expression [a-zA-Z]+|[0-9]+ matches any sequence of one or more letters or digits. The String.split() method can be called with this regular expression as an argument to split the input string into an array of substrings consisting of either letters or digits.

String input = "abc123def456";
String[] parts = input.split("[a-zA-Z]+|[0-9]+");

The resulting parts array contains the substrings {"abc", "def"} and {"123", "456"}, which represent the letters and digits in the input string, respectively.

Using Character Classes

Another way to split a Java String into letters and digits is to use character classes. The Character.isLetter() and Character.isDigit() methods can be used to test whether a character is a letter or a digit, respectively. The input string can be iterated over character by character, and each character can be added to a StringBuilder object if it is of the desired type. When a character of the opposite type is encountered, the StringBuilder object can be converted to a String and added to a List of substrings.

String input = "abc123def456";
List<String> parts = new ArrayList<>();
StringBuilder sb = new StringBuilder();

for (char c : input.toCharArray()) {
    if (Character.isLetter(c)) {
        if (sb.length() > 0) {
            parts.add(sb.toString());
            sb.setLength(0);
        }
    } else if (Character.isDigit(c)) {
        if (sb.length() > 0) {
            parts.add(sb.toString());
            sb.setLength(0);
        }
    }
    sb.append(c);
}

if (sb.length() > 0) {
    parts.add(sb.toString());
}

The resulting parts List contains the substrings {"abc", "123", "def", "456"}, which represent the letters and digits in the input string, respectively.

In conclusion, there are multiple ways to split a Java String into letters and digits, depending on the specific requirements of the task. Using regular expressions or character classes can provide efficient and robust solutions.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information