简体   繁体   中英

Java Method to find uppercase letters and numbers in a String

I'm fairly new to java and was wondering if there is a method that finds the uppercase letters in a string and also if there is method that finds the numbers in a string. Thank you

No, it is not a proprietary method.
You can use regular expression, or loop over letters in string and extract you need.

See some code here:
Extract digits from string - StringUtils Java
Extract digits from a string in Java

Please search first, before you ask a question.

The Java String API doesn't offer a method to do that specifically . You'll have to code it yourself using some of the methods String provides.

If you're a begginer, I'd suggest taking a look at Manipulating Strings in Java , also how do loops work in Java , and the Character class (specifically the isDigit() and isUpperCase() methods).

You can try

    for(Character c : s.toCharArray()){
        if(c.toString().toUpperCase().equals(c.toString())){
            System.out.println("Upper case");
        }
        else {
            System.out.println("Lower case");
        }
    }

So we convert String to character array, iterate over it and in each iteration we compare itself with it's the upper case to check what case is used.

and for finding number you can do something like below

    for(Character c : s.toCharArray()){

        try{
            Integer.parseInt(c.toString());
            System.out.println("Integer Identified");
        }catch (NumberFormatException ex){
            System.out.println("Not an integer");
        }
    }

For number simply parse String using Integer.parseInt() . If it is able to successfully parse then it is a number or if exception is thrown then it is not a number.

Since you haven't specified any plans for further processing the String, you can use something like this to find uppercase and digits:

public class Extraction {

  public static void main(String[] args) {
    String test = "This is a test containing S and 10";
    for (char c : test.toCharArray()) {
        if (Character.isDigit(c)) {
            System.out.println("Digit: " + c);
        }
        else if (Character.isUpperCase(c)) {
            System.out.println("Uppercase letter: " + c);
        }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM