2013-03-26 190 views
2

我有一個字符串數組,其中包含智能手機中可用的傳感器列表。 在我想要的每個元素的數組中,如果有匹配,則替換整個字符串。替換java中的整個字符串

例如:

sensor[1] = "iEnemoEngine orientation sensor"; 

我想如果sensor[1]包含單詞「方向」,更換整個字符串「iEnemoEngine方向感應器」與「方向」

我應該怎麼辦?

回答

7

試試這個:

if (sensor[1].contains("orientation")) { 
    sensor[1] = "orientation"; 
} 
+5

+1乾淨的代碼和簡單的正確的解決方案 – Johannes 2013-03-26 07:57:19

0
String orient = "orientation"; 

if(sensor[1].contains(orient)) sensor[1] = orient; 
0
String str = "iEnemoEngine orientation sensor"; 
String checkReplaceStr = "orientation"; 
if(str.contains(checkReplaceStr)){ 
    str = checkReplaceStr; 
} 

這應該在你的String陣列來實現對每個元素。

0

試試這個:

String pattern= "orientation"; 
for (int i=0; i<stringArray.length; i++){ 
    String str = stringArray[i]; 
    if (str.contains (pattern)){ 

    str = pattern; 
    stringArray[i] = str; 
    } 
}