總結:
- 語法層面上:這里主要用到Java字符串的替換函數,str.replaceAll("待替換的","替換成的")。replaceAll接受的是正則花的regex
- 還要注意替換不影響原來的字符串,只有左邊付給原來的字符串時,才達到徹底替換的結果。你也可以定義一個新的字符串去保存替換后的結果;
- 對於這種指定格式的輸入,只要考慮按照標准輸入就行了,而且按照這種標准輸入的話,還要對相關字符串進行提取,比如用正則化提取的“->”;
- 定義字符串數組:
(1)靜態的方法:String tmp[]=new String[2];
(2)動態的方法: ArrayList<String> strArray = new ArrayList<String> (); 比較靈活 或者Vector<String> vec=new Vector<String>; - 最后算法上沒有什么值得深究的地方;
題目要求:輸入一個字符串,然后在輸入一個整數,就是替換字符串的次數,然后依次輸入需要替換的字符串……
例如:
輸入:asdfghjasdfghj
3
as->bnm
df->qwe
gh->yui
輸出:bnmqweyuijbnmqweyuij
意思就是,將輸入的字符串中,as替換成bnm,df替換成qwe,gh替換成yui,總共替換三次,注意次數是不限定的,可以是任意整數等。
如果輸入的次數是2,舉例說明:
輸入:asdfgasdfg
2
as->bn
df->yuio
輸出:bnyuiogbnyuiog
電腦測試版本:
import java.util.*; public class StringReplace { public static void main(String[] args){ System.out.println("請輸入字符串:"); Scanner strOr=new Scanner(System.in); String strIn = strOr.nextLine(); System.out.println("請輸入要替換的個數:"); Scanner intOr=new Scanner(System.in); int count= intOr.nextInt(); String tmp[]=new String[2]; //分隔 String str[]=new String[count]; //保存 for(int i=0;i<count;i++){ Scanner strOr2=new Scanner(System.in); str[i]=strOr2.nextLine(); } for(int j=0;j<count;j++){ tmp=str[j].split("->"); //分隔存放到tmp中,這里是假設知道分隔后的長度 strIn=strIn.replaceAll(tmp[0], tmp[1]); } System.out.println(strIn); } }
提交版本:
import java.util.*; public class StringReplace { public static void main(String[] args){ // System.out.println("請輸入字符串:"); Scanner strOr=new Scanner(System.in); String strIn = strOr.nextLine(); // System.out.println("請輸入要替換的個數:"); Scanner intOr=new Scanner(System.in); int count= intOr.nextInt(); String tmp[]=new String[2]; //分隔 String str[]=new String[count]; //保存 for(int i=0;i<count;i++){ Scanner strOr2=new Scanner(System.in); str[i]=strOr2.nextLine(); } for(int j=0;j<count;j++){ tmp=str[j].split("->"); //分隔存放到tmp中,這里是假設知道分隔后的長度 strIn=strIn.replaceAll(tmp[0], tmp[1]); } System.out.println(strIn); } }