How to figure out if a character in a string is a number

This article will show how to figure out if a character in a string is a number. You might be wondering how to do it. There are multiple ways to determine if an individual or series of characters in the string classify as a number. So let’s look at various approaches for determining if the character is a number.

Using Character class

First option is to select a character from string with help of charAt() method and the character position; and use Character class static method isDigit() to return boolean value.

String movie = "101 dalmatians";
System.out.println(movie);
boolean result = Character.isDigit(movie.charAt(0));
System.out.println("Is first letter number? Answer: " + result)

The output will be:

101 dalmatians
Is first letter number? true

If we want to check if several characters are numbers, we can place the isDigit() method call inside the loop.

String movie = "101 dalmatians";
for (int i = 0; i <= movie.length() - 1; i++) {
    System.out.println(movie.charAt(i) + " -> " + Character.isDigit(movie.charAt(i)));
}

The output of the above code will be:

1 -> true
0 -> true
1 -> true
  -> false
d -> false
a -> false
l -> false
m -> false
a -> false
t -> false
i -> false
a -> false
n -> false
s -> false

Using Unicode check

Using Character class static method isDigit() can be used on any Unicode character, not just 0-9 number range. You can use create number check at any Unicode character.

Here is an example of checking a number through a check of Unicode characters:

String movie = "101 dalmatians";
System.out.println(movie);
boolean char c = word.charAt(0);
boolean isDigit = (c >= '0' && c <= '9');
System.out.println(isDigit)
101 dalmatians
true

Using Regex

Alternative way to using Character class static method isDigit() is to use solution based on regex output. However, this will require string to be instance of String class as we can conduct regex pattern search only on String.

Let us show you first regex pattern for searching digit in substring of length 1 on the instance String class named word:

word.substring(0, 1).matches("\\d")

The alternative and equivalent version uses the regex search pattern with the search of digit range.

word.substring(0, 1).matches("[0-9]")

The regex solution should be discouraged as it is an over-engineered solution. While there might be a minor performance hit, we can argue it would not affect simple coding solutions. But be aware that regex brings complexity. A solution implementing regular expression should be used with caution and with a fair amount of tests.

Note: Regular expressions are very strong, but expensive tool. It is valid to use regular expressions for character check if, e.g. the first character is a digit. But performance-wise, it is also like shooting birds with cannon.

Using casting

The last way to check if the character in a string is a number is to use Java casting feature. We will cast string values into one of the numerical object classes. However, this is the worst way how to do it. If you find a code using casting, you should refactor it immediately.

public boolean isNumber(String word) {
    boolean isNumber = true;
    try {
        Integer.valueOf(word.substring(0,1));
    } catch (Exception e) {
        isNumber = false;
    }
    return isNumber;
}

There is a lot that can go wrong with the method above. If the entering argument word is an empty string, casting will throw NumberFormatException and catch it. If the first character is not a digit, e.g. letter or special symbol, casting will also throw NumberFormatException and catch it. But if the first character is a digit, it will return true.

You can place any numerical object class to the code such as Integer, Double, Float or Long. But please do not! Using casting with valueOf() method is wrong for two reason:

  • In general, we want to avoid throwing Exceptions, checked or unchecked, as they slow the program and have tremendous performance hit.
  • Second reason, we can see above at least 3 different ways which provide shorter, more effective and readable way for solving the same problem.

Conclusion

In the article, we have demonstrated four different ways to find out if the single character or characters from a string is a number or not. The solutions ranged from best to worst, from easiest to most cumbersome. Use as much as possible the first option which use Character class static method isDigit() for determining if the character is a string. Using isDigit() method is, without instantiation of any variables, the most effective and readable solution.

I hope you learned something new and had fun. Thanks for the reading. And if you have any tricks or know a better way how to find out if the character is a string, let us know in the comments below. We would like to hear your ideas.

This entry was posted in Tips & tricks and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.