Priyadharshini KS
Priyadharshini KS

Reputation: 23

Print alphabets and numeric given in one string separately in java

Given a string with alphabetical, numeric, and special characters - for example String s= "abc12$%" - print the alphabetical, numeric and special characters separately. Without changing the string into character!

Answer:

Alphabet: abc
numeric: 12
special character: $%

Help me with the Java code..

Upvotes: 1

Views: 1961

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

You didn't show much effort here, but String#replaceAll is well-suited to this problem. We can try removing classes of characters which don't match what we want to target.

String input = "abc12$%";
System.out.println("alphabet: " + input.replaceAll("(?i)[^A-Z]+", ""));
System.out.println("numeric: " + input.replaceAll("[^0-9]+", ""));
System.out.println("symbol: " + input.replaceAll("(?i)[A-Z0-9]+", ""));

This prints:

alphabet: abc
numeric: 12
symbol: $%

Here is an explanation of the regex patterns used above. Note that we replace with empty string in all cases, so we are matching what we want to remove.

(?i)[^A-Z]+    match any non letter, case insensitive (?i)
[^0-9]+        match any non digit
(?i)[A-Z0-9]+  match any alphanumeric character (i.e. a letter or number)

Upvotes: 1

A_rmas
A_rmas

Reputation: 784

This is a logical question, so I prefer only to give idea instead of exact solution.

Try this:

read the ASCII value of each character in string, analyze which character falls in which range of ASCII values, add each character in 3 different array each for alphabet, number and special character, and finally print all the array in string.

Upvotes: 0

Related Questions