我有一個字符串ArrayList組成的字母表,後跟一個數字作爲每個字母表的後綴。從引用字符串中替換字符串的一部分
ArrayList <String> baseOctave = new ArrayList();
baseOctave.add("S1");
baseOctave.add("R2");
baseOctave.add("G4");
baseOctave.add("M2");
baseOctave.add("P3");
baseOctave.add("D1");
baseOctave.add("N1");
我把這個baseOctave和其他幾個字符的字符串作爲輸入模式來創建一個對象。 MyClass obj1 = new MyClass(「S1,R2,M2」 - 「); 由於我經常使對象實例化期間使用這些種輸入模式,我想用簡單的字符S,R,G,M等 例:
MyClass obj1 = new MyClass ("S,,R.,M''-");
MyClass obj2 = new MyClass ("S1,G.,M,D1");
所以對象創建過程中使用的字母表可以包含數字作爲後綴或它可能沒有數字作爲後綴。
但是在構造函數中(或在單獨的方法中),我想用帶有後綴的字母替換這些簡單的字母。後綴取自baseOctave。 例:以上OBJ1和obj2的兩個字符串應該是 「S1,R2,M2 '' - 」 和 「S1,G4,M2,D1」
我綁要做到這一點,但不能繼續代碼如下。需要一些幫助,更換,請..
static void addSwaraSuffix(ArrayList<String> pattern) {
for (int index = 0; index < pattern.size(); index++) {
// Get the patterns one by one from the arrayList and verify and manipulate if necessary.
String str = pattern.get(index);
// First see if the second character in Array List element is digit or not.
// If digit, nothing should be done.
//If not, replace/insert the corresponding index from master list
if (Character.isDigit(str.charAt(1)) != true) {
// Replace from baseOctave.
str = str.replace(str.charAt(0), ?); // replace with appropriate alphabet having suffix from baseOctave.
// Finally put the str back to arrayList.
pattern.set(index, str);
}
}
}
編輯信息如下: 感謝您的回答。我發現了另一種解決方案,並且工作正常下面是我發現的完整代碼。讓我知道是否有任何問題。
static void addSwaraSuffix(ArrayList<String> inputPattern, ArrayList<String> baseOctave) {
String temp = "";
String str;
for (int index = 0; index < inputPattern.size(); index++) {
str = inputPattern.get(index);
// First see if the second character in Array List is digit or not.
// If digit, nothing should be done. If not, replace/insert the corresponding index from master list
// Sometimes only one swara might be there. Ex: S,R,G,M,P,D,N
if (((str.length() == 1)) || (Character.isDigit(str.charAt(1)) != true)) {
// Append with index.
// first find the corresponsing element to be replaced from baseOctave.
for (int index2 = 0; index2 < baseOctave.size(); index2++) {
if (baseOctave.get(index2).startsWith(Character.toString(str.charAt(0)))) {
temp = baseOctave.get(index2);
break;
}
}
str = str.replace(Character.toString(str.charAt(0)), temp);
}
inputPattern.set(index, str);
}
}
您的圖案元素將永遠是一個字符用一個數字?縮寫總是一個字符? – Aivean 2014-09-25 18:00:11
正確。我有很多baseOctave的實例,它總是有以下組合:字母S,R,G,M,P,D,N,後面跟着1-4個數字。例如:S1 R2 S4 G1 G4 M3 P1然而,我的模式可能省略這些後綴以便於處理。所以我會通過基礎八度,然後模式,以便根據基礎八度,模式將被修改,以包括這些後綴。 – 2014-09-26 03:33:06