使用者自行輸入一個字串以及想要移除的字元
透過substring 以及遞迴的概念 將字串進行移除- [hide]import java.util.Scanner;
- public class JPD04 {
- static Scanner keyboard = new Scanner(System.in);
- public static void main(String args[]) {
- String s, c;
- System.out.print("Input a string: ");
- s = keyboard.nextLine();
- System.out.print("Input a character: ");
- c = keyboard.nextLine();
- System.out.printf("%s\n", removeChar(s, c));
- System.out.print("Input a string: ");
- s = keyboard.nextLine();
- System.out.print("Input a character: ");
- c = keyboard.nextLine();
- System.out.printf("%s\n", removeChar(s, c));
- }
-
- public static String removeChar(String s,String c)
- {
- // HAHA ,A
- // H + AHA ,A
- // AHA,A
- // HA,A
- // H A,A
- // A,A
- // "" ,A
- if(s.equals(""))
- {
- return "";
-
- }
- else if (s.substring(0,1).equals(c))
- {
- return removeChar(s.substring(1),c);
- }
- else {
- return s.substring(0,1)+removeChar(s.substring(1),c);
- }
-
- // s.substring(0,1)+ s.substring(0,1) + s.substring(0,1) + s.substring(0,1)
- }
-
- }[/hide]
複製代碼 |