Replace the ' by \'

I'm trying to replace a single quote ' with this character \', the final goal is to transform this chay'ekka to chay\'ekka. I tried this code:

String cityName = new String("chay'ekka");
System.out.println("before : " + cityName);
cityName = cityName.replaceAll("'", "\\'");
System.out.println("after : " + cityName);

but the result is still chay'ekka.

Are there any other methods or functions in java to achieve this goal?

Jon Skeet
people
quotationmark

You're using replaceAll, which works with regular expressions. While you can fix that by doubling the backslashes, there's no indication that you want regular expressions at all. It would be simpler just to call String.replace instead, as that doesn't use regular expressions:

String cityName = new String("chay'ekka");
System.out.println("before : " + cityName);
cityName = cityName.replace("'", "\\'");
System.out.println("after : " + cityName);

Note that replace still replaces all occurrences of the first argument with the second argument - the naming between replace and replaceAll is poor :( It would be better as replace vs replaceRegex or something similar.

people

See more on this question at Stackoverflow