How to Replace a Character in a String in Java

Replace a character at a specific index in a string?

String are immutable in Java. You can't change them.

You need to create a new string with the character replaced.

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

Java replace ' 'character with ' \ '

Double escape the \ like so:

givenString.replaceAll("\"", "\\\"");

As stated by Ted Hopp in comments, for inserting data into a table you should user prepared statements using parameters, and set them according to the API you are using. For example if you are using JDBC you may use the setString method of your Statement object.

String str = "Hello \"world";
PreparedStatement stmt = con.prepareStatement(
"insert into mytable('column') values(?)");
stmt.setString(1, str);

About your first comment:

In Java Strings are immutable, so replaceAll returns a new instance whose contents is the string with the required replacements. So what you want is to assign again the result to the previous variable, like so:

public String getSqlLikeString(String givenString) {
System.out.println(givenString);
givenString = givenString.replaceAll("\"", "\\\"");
System.out.println(givenString);
return givenString;
}

// or just
public String getSqlLikeString(String givenString) {
return givenString.replaceAll("\"", "\\\"");
}

Java: Replace a specific character with a substring in a string at index

String[][] arr = {{"1", "one"}, 
{"5", "five"}};

String str = "String5";
for(String[] a: arr) {
str = str.replace(a[0], a[1]);
}

System.out.println(str);

This would help you to replace multiple words with different text.

Alternatively you could use chained replace for doing this, eg :

str.replace(1, "One").replace(5, "five");

Check this much better approach : Java Replacing multiple different substring in a string at once (or in the most efficient way)

Java replace initial characters in String and preserve length

Java supports finite repetition in a lookbehind. You could match a asserting what is on the left from the start of the string are only a's.

In the replacement using -

(?<=^a{1,100})a

Regex demo | Java demo

For example

System.out.println("aaabbaa".replaceAll("(?<=^a{0,100})a", "-"));

Output

---bbaa

Replace a string character by only using charAt()

Just loop through the String and if the charAt(i) is equal to your specific char, then append the replacement, otherwise append the charAt(i)

public static String replaceCharacter(String w, char b, String v) {
String result = "";
for (int i = 0; i < w.length(); i++) {
if (w.charAt(i) == b) {
result += v;
} else {
result += w.charAt(i);
}
}
return result;
}

Demo



Related Topics



Leave a reply



Submit