John Christy
John Christy

Reputation: 373

Find character in a number which is in String format

How can I find a string in a number?

A simple example is follows

private char check() {
        String sample ="1212kkk";//121hhh444 | 12-22
        return 'k';//'h' | '-'

    }

If anything other than number I want to return that value.

How can I get the first character from this ring?

Upvotes: 0

Views: 113

Answers (6)

oe.elvik
oe.elvik

Reputation: 505

private char check() {
    String sample ="1212kkk";//121hhh444 | 12-22
    return sample.replaceAll("[0-9]+", "").charAt(0);

}

Upvotes: 1

dantuch
dantuch

Reputation: 9293

try with guava

CharMatcher.indexIn

something like: if(CharMatcher.JAVA_LETTER.indexIn(yourString) != -1) return yourString.charAt(CharMatcher.JAVA_LETTER.indexIn(yourString));

public static void main(String[] args) {
    String yourString = "123abc";
    int indexOfLetter = CharMatcher.JAVA_LETTER.indexIn(yourString);
    if (indexOfLetter != -1) {
        char charAt = yourString.charAt(indexOfLetter);
        System.out.println(charAt);
    }
}

prints a

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You need to change the signature of your method, otherwise the caller would not be able to tell when the string is "good" (i.e. contains only digits). One way would be returning Character, a wrapper around the char primitive.

Inside, you can use a simple regex [^0-9] to match the first non-digit in a String. When there is no match, return null. This way the callers would be able to call your method like this:

private static Character check(String s) {
    Pattern firstNonDigit = Pattern.compile("[^0-9]");
    Matcher m = firstNonDigit.matcher(s);
    if (m.find()) {
        return m.group().charAt(0); // The group will always be 1 char
    }
    return null; // Only digits or no characters at all
}
...
Character wrongChar = check("12-34");
if (wrongChar != null) {
    ...
}

Upvotes: 1

kiriloff
kiriloff

Reputation: 26333

\D is a non-digit, and so then \D* is any number of non-digits in a row. So your whole string should match \D*.

    Matcher m = Pattern.compile("\\D*").matcher(sample);
    while (m.find()) {
        System.err.println(m.group());
    }

Try with \\D* and \D* please.

Upvotes: 0

loomie
loomie

Reputation: 616

Am I something getting wrong? If you save something as an int(number) you can't have a string value in there. If you, however mean, that you have a string, and in its string numbers, and want to get only the numbers, this regex command will get all number digits

/(\d+)/

Upvotes: 0

Achintya Jha
Achintya Jha

Reputation: 12843

Try this:

String result = sample.replaceAll("\\d" ,"");
return result;

Upvotes: 1

Related Questions