問題 A: 刪除指定字符
時間限制: 1 Sec 內存限制: 64 MB
提交: 2384 解決: 1864
[提交] [狀態] [命題人:外部導入]
題目描述
從鍵盤輸入一個字符串給str和一個字符給c,刪除str中的所有字符c並輸出刪除後的字符串str。
輸入
第一行是一個字符串; 第二行是一個字符。
輸出
刪除指定字符後的字符串。
樣例輸入 Copy
sdf$$$sdf$$
$
樣例輸出 Copy
sdfsdf
解法1:replace(CharSequence target,CharSequence replacement);
(前一個參數是目標序列,其實就是你要替換掉的字符串,第二個參數是你要替換成的字符串);
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO 自動生成的方法存根
Scanner scan = new Scanner(System.in);
String bef = scan.nextLine();
char c = scan.next().charAt(0);
//int i,j;
String s = bef.replace(c+"", "");
System.out.println(s);
}
}
注意事項:String類型是一個不變類型,你要新建一個變量接收它。
解法2:一次判斷字符串的每一個字符
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO 自動生成的方法存根
Scanner scan = new Scanner(System.in);
String bef = scan.nextLine();
char c = scan.next().charAt(0);
for(int i=0;i<bef.length();i++) {
if(bef.charAt(i)!=c) {
System.out.print(bef.charAt(i));
}
}
System.out.println();
}
}
解法3:StringBuffer是一個可變類型,因此可以直接替換後輸出,但是,注意,正因爲它的可變,所以你纔要注意你的for循環,計數器的變化。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO 自動生成的方法存根
Scanner scan = new Scanner(System.in);
StringBuffer bef = new StringBuffer();
String rec = scan.nextLine();
bef.append(rec);
char c = scan.next().charAt(0);
for(int i=0;i<bef.length();i++) {
if(bef.charAt(i)==c) {
bef.deleteCharAt(i);
i--;
}
}
System.out.println(bef);
}
}