1

I am working on android. I have a string containing huge data. In that string I want to replace a particular character to another character. I got the index of the character which I want to replace. But I am unable to replace that character. How can I do that?

String str = "data1data2mdata2test1test2test3dd" 

int ind = str.indexOf("m");
System.out.println("the index of m" + ind);

Now in the above string I want to replace the character "m"(after data2) to "#".

Now how can I replace the m to #. Please help me in this reagard.

Amrutha
  • 575
  • 4
  • 9
  • 29
  • 1
    Don't forget to search first : http://stackoverflow.com/questions/6952363/java-replace-a-character-at-a-specific-index-in-a-string – nioKi Aug 06 '13 at 07:36

4 Answers4

3

You can use substring:

String newStr = str.substring(0, ind) + '#' + str.substring(ind + 1);
Brtle
  • 2,297
  • 1
  • 19
  • 26
3

Try this: str = str.replaceFirst("m", "#");

It will replace the first m to #

Renan Bandeira
  • 3,238
  • 17
  • 27
2
String str1 = "data1data2mdata2test1test2test3dd"

    String str = str1.replace("m", "#");
    System.out.println(str);
Robi Kumar Tomar
  • 3,418
  • 3
  • 20
  • 27
  • `replace` returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. – Boris Mocialov Aug 06 '13 at 07:37
  • Yaa Boris I forgot to mention here,It can achieve this in such a way: StringBuilder str = new StringBuilder("data1data2mdata2test1test2test3dd"); str.setCharAt(9, '#'); System.out.println(str); – Robi Kumar Tomar Aug 06 '13 at 11:29
0

So you are getting 10 as system out, so this way you can replace it like,

Str.replace('m', '#')--->when you want all occurrences of it to replace it,

Or if you want only first occurrence to be replaced by # then you can do following trick,

StringBuffer buff=new StringBuffer();
buff.append(Str.substring(0,ind)).append("#").append(Str.substring(ind+1));

i hope it would help

user2408578
  • 464
  • 1
  • 4
  • 13