-3

I have this exercise. Why not work with replaceAll? I have an error: String index out of range: 1

 public class e3 {

    public static void main(String[] args) {
        String x="Sessione successiva";
        String nuova=x.replace("i", "!");
        String nuova2=nuova.replace("s", "$");
        String nuova3=nuova2.replace("e", "&");
        System.out.println(nuova3);

            //replaceAll
        String nuovaz=x.replaceAll("i", "!");
        String nuova2z=nuovaz.replaceAll("s", "$");
        String nuova3z=nuova2.replaceAll("e", "&");
        System.out.println(nuova3z);


    }

}
1
  • 1
    String nuova3z=nuova2.replaceAll("e", "&"); there is a mistake, nuova2 should be nuova2z. Commented Dec 29, 2014 at 12:15

2 Answers 2

3

replaceAll works with regular expressions. In the replacAll method, $ is a reserved character used to reference groups defined in the regular expression given as first parameter, so you need to escape it.

String nuova2z=nuovaz.replaceAll("s", "\\$");

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

You need to escape characters which are use in regular expression, try following:

String nuovaz=x.replaceAll("i", "!");
String nuova2z=nuovaz.replaceAll("s", "\\$");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.