繁体   English   中英

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

[英]removing characters from string using a method in java

我正在尝试编写一种方法来接收字符串作为参数,并从中删除所有空格和标点符号,所以这是我的想法。

    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;



    }
}

现在,我只添加了text = normalize Text(text); 然后将其打印出来,因为如果没有它,它将无法将其打印到屏幕上(即使在某些方法中,返回值实际上会在屏幕上显示输出),即使此更改也无济于事,因为它不会从中删除任何内容方法接收的字符串会打印出完全相同的字符串..有帮助吗? 提前致谢 。 :)

您的代码中的问题是,您尚未分配回在s.replace(“:”,“”);之后生成的新字符串; 请记住,字符串是不可变的,因此by replace方法的更改将不适用于调用该方法的字符串对象。

你应该写的

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

您可以像这样编写方法,而不用繁琐的normalizeText方法:

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

每次替换后,您都需要对字符串进行赋值 ,例如

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

    s = s.toUpperCase();

    return s;
}

但是请注意,我们可以轻松地使用一个正则表达式来处理您的替换逻辑:

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