简体   繁体   English

使用Java中的方法从字符串中删除字符

[英]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); 现在,我只添加了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(":",""); 您的代码中的问题是,您尚未分配回在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. 请记住,字符串是不可变的,因此by replace方法的更改将不适用于调用该方法的字符串对象。

You should have written, 你应该写的

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

Instead of your tedious method normalizeText you can write your method like this, 您可以像这样编写方法,而不用繁琐的normalizeText方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM