dagav
dagav

Reputation: 47

Remove all spaces and punctuation (anything not a letter) from a string?

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

Upvotes: 1

Views: 30261

Answers (5)

Hemanth Chowdary
Hemanth Chowdary

Reputation: 96

public static String repl1(String n){
    n = n.replaceAll("\\p{Punct}|\\s","");
    return n;
}

Upvotes: 1

Siddharth Choudhary
Siddharth Choudhary

Reputation: 1129

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!!

Upvotes: 1

ltalhouarne
ltalhouarne

Reputation: 4636

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

Upvotes: 2

C.B.
C.B.

Reputation: 8326

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.

Upvotes: 6

Tolis Stefanidis
Tolis Stefanidis

Reputation: 31

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);

Upvotes: -2

Related Questions