简体   繁体   中英

removing characters from string using a method in java

I'm trying to write a method to take in a string as a parameter and remove all whitespaces and punctuation from it so this is my idea of how to do that..

    import java.util.*;
public class Crypto {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print("Please insert the text you wish to encrypt: ");
        String text = input.nextLine();
        text = normalizeText(text);
        System.out.println(text);
    }

    public static String normalizeText(String s){
            s.replace(" ","");
            s.replace("(","");s.replace(")","");s.replace(".","");
            s.replace(",","");s.replace("?","");s.replace("!","");
            s.replace(":","");s.replace("'","");s.replace("\"","");
            s.replace(";","");

            s.toUpperCase();
            return s;



    }
}

Now , I only added the text = normalize Text(text); and then printed it because it wouldn't print it to the screen without it( even though in some methods the return would actually show an output on the screen) anyway, even this change didn't help because it doesn't remove anything from the string taken in by the method it prints out the exact same string.. any help? Thanks in advance . :)

Problem in your code is, you haven't assigned back the new string that got generated after s.replace(":",""); Remember, strings are immutable so the change by replace method will not apply to the string object on which you call the method.

You should have written,

s = s.replace(":", "")

Instead of your tedious method normalizeText you can write your method like this,

public static String normalizeText(String s){
    return s.replaceAll("[ ().,?!:'\";]", "").toUpperCase();
}

You need to make assignments to the string after each replacement has been made, eg

public static String normalizeText(String s) {
    s = s.replace(" ", "");
    s = s.replace("(","");
    // your other replacements

    s = s.toUpperCase();

    return s;
}

But note that we can easily just use a single regex to handle your replacement logic:

public static String normalizeText(String s) {
    s = s.replaceAll("[().,?!:'\"; ]", "").toUpperCase();

    return s;
}

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