Klausos Klausos
Klausos Klausos

Reputation: 16050

How to obtain numeric and non-numeric values from a String

Let's say there are three strings:

String s1 = "6A";
String s2 = "14T";
String s3 = "S32";

I need to extract numeric values (i.e. 6,14 and 32) and characters (A,T and S).

If the first character was always a digit, then this code would work:

int num = Integer.parseInt(s1.substring(0,1));

However, this is not applicable to s2 and s3.

Upvotes: 0

Views: 2645

Answers (4)

user4571931
user4571931

Reputation:

You can use java.util.regex package which is consists two most important classes

1) Pattern Class

2) Matcher Class

Using this classes to get your solution.

For more details about Pattern and Matcher Class refer below link

http://www.tutorialspoint.com/java/java_regular_expressions.htm

Below is the complete example

public class Demo {
public static void main(String[] args) {
    String s1 = "6A";
    String s2 = "14T";
    String s3 = "S32";

    Pattern p = Pattern.compile("-?\\d+");
    Matcher m = p.matcher(s3);
    while (m.find()) 
    {
        System.out.println(m.group());
    }

}
}

If you need string and wants to skip numeric value then use below pattern.

Pattern p = Pattern.compile("[a-zA-Z]");

Upvotes: 1

pL4Gu33
pL4Gu33

Reputation: 2085

You can make something like that:

public static int getNumber(String text){
    return Integer.parseInt(text.replaceAll("\\D", ""));
}

public static String getChars(String text){
    return text.replaceAll("\\d", "");
}

public static void main(String[] args) {
    String a = "6A";
    String b = "14T";
    String c = "S32";

    System.out.println(getNumber(a));
    System.out.println(getChars(a));
    System.out.println(getNumber(b));
    System.out.println(getChars(b));
    System.out.println(getNumber(c));
    System.out.println(getChars(c));
}

Output:

6 A 14 T 32 S

Upvotes: 4

maxormo
maxormo

Reputation: 629

Yo can check whether first character in a string is a letter if yes then do

Integer.parseInt(s1.substring(1))

Means parse from second character

Upvotes: -2

P Griep
P Griep

Reputation: 844

Try this:

String numberOnly = s1.replaceAll("[^0-9]", "");
int num = Integer.parseInt(numberOnly);

Or the short one:

int num = Integer.parseInt(s1.replaceAll("[^0-9]", ""));

The code is applicable for s2 and s3 as well!

Upvotes: 3

Related Questions