1

In Java, how can I take a string as a parameter, and then remove all punctuation and spaces and then convert the rest of the letters to uppercase?

Example 1:

Input: How's your day going?

Output: HOWSYOURDAYGOING

Example 2:

Input: What's your name again?

Output: WHATSYOURNAMEAGAIN

Random
  • 431
  • 8
  • 20
dagav
  • 47
  • 1
  • 1
  • 5

5 Answers5

6

This should do the trick

String mystr= "How's your day going?";
mystr = mystr.replaceAll("[^A-Za-z]+", "").toUpperCase();
System.out.println(mystr);

Output:

HOWSYOURDAYGOING

The regex [^A-Za-z]+ means one or more characters that do not match anything in the range A-Za-z, and we replace them with the empty string.

C.B.
  • 8,096
  • 5
  • 20
  • 34
2
String yourString = "How's your day going";
yourString=yourString.replaceAll("\\s+",""); //remove white space
yourString=yourString.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
yourString=yourString.toUpperCase(); //convert to Upper case
Edward Dan
  • 134
  • 1
  • 10
ltalhouarne
  • 4,586
  • 2
  • 22
  • 31
  • You can still kill off your 2nd line and have your regex handle all characters not in `a-z` and `A-Z` – admdrew Feb 21 '14 at 22:25
  • Why people keep posting solutions which doesn't contemplate other languages like asian languages? – David Apr 26 '20 at 11:38
1

I did it with

inputText = inputText.replaceAll("\\s|[^a-zA-Z0-9]","");


inputText.toUpper();  //and later uppercase the complete string

Though @italhourne 's answer is correct but you can just reduce it in single step by just removing the spaces as well as keeping all the characters from a-zA-Z and 0-9, in a single statement by adding "or". Just a help for those who need it!!

Siddharth Choudhary
  • 1,069
  • 1
  • 15
  • 20
1
public static String repl1(String n){
    n = n.replaceAll("\\p{Punct}|\\s","");
    return n;
}
-2

Well, I did it the long way, take a look if you want. I used the ACII code values (this is my main method, transform it to a function on your own).

String str="How's your day going?";
    char c=0;
    for(int i=0;i<str.length();i++){
        c=str.charAt(i);
        if(c<65||(c>90&&c<97)||(c>122)){
            str=str.replace(str.substring(i,i+1) , "");
        }
    }
    str=str.toUpperCase();
    System.out.println(str);