Ashwini Balan
Ashwini Balan

Reputation: 11

How to replace a word from a string in android

I have a string, with value hi, how r u{name}; And also I have an Array of size 3 I want to find the word " {name} " from the string and replace it with current array value a[i]. I have try to this code

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]);
}

Upvotes: 1

Views: 315

Answers (4)

Robin Dijkhof
Robin Dijkhof

Reputation: 19288

Something this is what you need

        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];
        }

Upvotes: 1

SpringLearner
SpringLearner

Reputation: 13844

As the question is not clear,I assume that this part is not working Amith.replace("{Name}", Questions[i]); meaning that the string amith is not getting replaced.you need to do Amith=Amith.replace("{Name}", Questions[i]); As String is immutable,The result of String.replace() is a new String with the replaced value.

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]);
}

Upvotes: 0

Triode
Triode

Reputation: 11359

public String replace (CharSequence target, CharSequence replacement) Added in API level 1

Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end. Parameters target the sequence to replace. replacement the replacement sequence. Returns

the resulting string.

Throws NullPointerException if target or replacement is null.

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

Upvotes: 1

M-Wajeeh
M-Wajeeh

Reputation: 17284

Do it like this:

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

Upvotes: 0

Related Questions