[英]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.