Reputation: 39
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
Upvotes: 0
Views: 8867
Reputation: 68905
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.
Upvotes: -1
Reputation: 27880
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).
Upvotes: 0
Reputation: 1634
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);
}
}
}
}
Upvotes: -1
Reputation: 2703
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.
Upvotes: 0