如何在android中替换字符串中的单词

时间:2013-12-17 10:54:13

标签: java android

我有一个字符串,值为hi,如何使用{name}; 而且我还有一个3号阵列 我想从字符串中找到单词“{name}”,并将其替换为当前数组值a [i]。 我试过这段代码

Resources res = getResources ();
String []Questions=res. getStringArray (R.array.faq_ques);

int Questions_Array_length = Questions .length;

for(i=0; i<Questions_Array_length; i++) {
  String Amith= "hi how r u {Name}";
  Amith.replace("{Name}", Questions[i]);
}

4 个答案:

答案 0 :(得分:1)

  

public String replace (CharSequence target, CharSequence replacement)   在API级别1中添加

     

复制此字符串,替换指定目标的出现次数   序列与另一个序列。字符串是从。处理   从头到尾。参数以要替换的序列为目标。   更换更换顺序。返回

the resulting string.
     

如果target或replacement为null,则抛出NullPointerException。

Amith = Amith.replace("{Name}", Questions[i]);

答案 1 :(得分:1)

这就是你需要的东西

        String sentence = "hello what is your name";
        String[] words = sentence.split(" ");
        for(int i = 0; i<words.length; i++){
            if(words[i].equals("Your String")){
                words[i] = "Your New String";
            }
        }

        String newSentence = "";
        for(int i = 0; i<words.length; i++){
            newSentence += words[i];
        }

答案 2 :(得分:0)

这样做:

Amith = Amith.replace("{Name}", Questions[i]);

答案 3 :(得分:0)

由于问题不明确,我认为这部分不起作用Amith.replace("{Name}", Questions[i]);意味着string amith没有被替换。你需要做Amith=Amith.replace("{Name}", Questions[i]);因为String是不可变的, String.replace() 的结果是带有替换值的新字符串

Resources res = getResources ();
String []Questions=res. getStringArray (R.array.faq_ques);

int Questions_Array_length = Questions .length;
for(i=0;i<Questions_Array_length;i++)
{
  String    Amith= "hi how r u {Name}";
  Amith=Amith.replace("{Name}", Questions[i]);
}