[問題] 在String中插入多個String(類似字典

作者: gcobc12632 (Ted)   2017-06-15 15:27:26
原本我假設是這樣:
String str = "這是一個測試的字串";
ArrayList<String> inputA = new ArrayList<>(); // 要插入的字串A
ArrayList<Integer> indexA = new ArrayList<>(); // 要插入的字串A的位置
inputA.add("0");
inputA.add("2");
inputA.add("4");
inputA.add("6");
indexA.add(0);
indexA.add(2);
indexA.add(4);
indexA.add(6);
然後將字串插入:
int count = 0;
for(int i = 0; i < indexA.size(); i++) {
str = str.substring(0, indexA.get(i) + count)
+ inputA.get(i) // 插入字串
+ str.substring(indexA.get(i) + count);
count++;
}
正確結果:
0這是2一個4測試6的字串
但是如果我插入兩個以上的字串就不知道該怎麼處理了…
ArrayList<String> inputB = new ArrayList<>(); // 要插入的字串B
ArrayList<Integer> indexB = new ArrayList<>(); // 要插入的字串B的位置
inputB.add("a");
inputB.add("b");
inputB.add("c");
indexB.add(2);
indexB.add(3);
indexB.add(4);
然後加上上面的結果應該要是:
(如果字串A跟字串B在同一個位置,字串B要在字串A後面)
0這是2a一b個4c測試6的字串
這裡原本是想寫成像字典的註解那樣,
但是註解有兩種以上,插入的位置就很難抓了…
有人知道這裡該怎麼寫嗎?
想了兩天還是想不出來…
作者: ssccg (23)   2017-06-15 15:59:00
先照要插入的位置排序,依序插入,每個插入位置要加上前面已插入字串的長度總和
作者: zcbxvsdf (東北一頭羊)   2017-07-02 23:58:00
先把B,C,D...的合併到A再做插入B-index跑迴圈,判斷A-Index是否contains,再對A-Input那個index做set A+B,三個以上Input以此類推,最後A再對原文合併

Links booklink

Contact Us: admin [ a t ] ucptt.com