To remove all UPPERCASE letters from a string:
String repl = sir.replaceAll("[A-Z]+", "");
To copy all UPPERCASE letters from a string to another string:
String upper = sir.replaceAll("[^A-Z]+", "");
Question
I need to check if in my String "sir" i have some uppercase letters, if so, i need to assign the value of that letter to another string and then to delete the letter. my first part looks like this:
Pattern p = Pattern.compile("[^A-Z]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(sir);
boolean b = m.find();
so that i check if there is any uppercase letter, then i need to add assigning & deleting. i am not sure if this works. also i found another way:
StringTokenizer stringTokenizer = new StringTokenizer(sir);
while (stringTokenizer.hasMoreTokens()) {
String a = stringTokenizer.nextToken();
if(a.equals(a.toUpperCase())) {
upper = a;
}
}
upper returns null everytime, even though sir = cL
does anyone know a way to:
any help would be much appreciated.
Solution
To remove all UPPERCASE letters from a string:
String repl = sir.replaceAll("[A-Z]+", "");
To copy all UPPERCASE letters from a string to another string:
String upper = sir.replaceAll("[^A-Z]+", "");
OTHER TIPS
This will give you all the capital letters in a string:
String inputString;
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
ouptutString += Character.isUpperCase(c) ? c + " " : "";
}
You can also try "guava" libriaries. There you can find set of classes for string manipulation. Among them CharMatcher (https://code.google.com/p/guava-libraries/wiki/StringsExplained#CharMatcher)
simple code example can be:
String string = "ABcdEFgh45";
String withoutUpperCase = CharMatcher.JAVA_UPPER_CASE.removeFrom(string);
//returns cdgh45