-1

i am trying to replace all occurrences of the first character in a string with another using the replace all function. However, no change occurs when i run the function. I tried to target the first character of the original string and then carry the out the replacement but no luck. Below is a snippet of my code.

public static String charChangeAt(String str, String str2) {  

    //str = x.xy
    //str2 = d.w

    String res = str.replaceAll(Character.toString(str.charAt(0)), str2);

    return res ;
}  
Kars
  • 845
  • 1
  • 14
  • 33
Chev
  • 1
  • 2
  • For me, `System.out.println(charChangeAt("d.dx", "d.w"));` outputs: `d.w.d.wx`. Something must be going wrong somewhere else. How are you calling this method? – mypetlion Apr 05 '19 at 21:07
  • i was trying to call it in a loop. So basically i'm cycling through an array of strings and changing occurrences of the first character to something else for the string in question. – Chev Apr 06 '19 at 04:10

3 Answers3

0

Your code replaces all characters that match the first character. If your string is abcda and you run your function, it will replace all occurences of a with whatever you put. Including the last one.

To achieve your goal you should probably not use replaceAll.

You could use StringBuilder.

StringBuilder builder = new StringBuilder(str);
myName.setCharAt(0, str2.charAt(0));
Kars
  • 845
  • 1
  • 14
  • 33
0

Your function works fine but you probably are using it the wrong way.
For these strings:

String str = "abaca";
String str2 = "x";

if you do:

charChangeAt(str, str2);

this will not affect str.
You must assign the value returned by your function to str:

str = charChangeAt(str, str2);

This will change the value of str to:

"xbxcx"
forpas
  • 160,666
  • 10
  • 38
  • 76
0

In case you want to replace all occurrences of the first character in a string with another, you can use replace instead of replaceAll. Below is the code snippet.

String str = "x.xy";
String str2 = "d.w";
String res = str.replace(Character.toString(str.charAt(0)), str2);
return res; // will output d.w.d.wy