0

The following code prints eleelde but I want it to print elcaalde.

How can I do it? Is there a function like replace char at index()??

I want to assign the character at i=0 the value of the char at i=6 and print the word elcaalde.

public class ReverseExperiments3 {  
   public static void main (String[] args) {
      String s= "alcaalde";
      s=s.replace('a','e'); 
      System.out.println(s);
   }
}
stefanobaghino
  • 11,253
  • 4
  • 35
  • 63

3 Answers3

2

Change it in the char array:

char[] cs = s.toCharArray();
cs[0] = cs[6];  // For example.
s = new String(cs);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • in order to achieve the result, it is 7th element and so s[7]. Anyways, you were right giving it as s[6] as he asked for it – Jayanth Feb 08 '18 at 09:32
0

You could also use a regex replacement here:

String s = "alcaalde";
s = s.replaceFirst("(.)(.{6})(.)", "$3$2$1");

Demo

The answer given by @andy is probably the best one for this exact problem. But if the OP needed to move around strings, then a regex based approach would put us in a fairly good position.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

try this code: If you wanna get what you want, it is 7th element

String s= "alcaalde";
char[] cs = s.toCharArray();
cs[0] = cs[7];  
s = new String(cs);
Jayanth
  • 746
  • 6
  • 17