EN
Java - replace first character in string
0 points
In this article, we would like to show you how to replace the first character in string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABC";
2
String replacement = "x";
3
String result = replacement + text.substring(1);
4
5
System.out.println(result); // xBC
or:
xxxxxxxxxx
1
String text = "ABC";
2
String replacement = "x";
3
String result = replacement.concat(text.substring(1));
4
5
System.out.println(result); // xBC
or:
xxxxxxxxxx
1
String text = "ABC";
2
String replacement = "x";
3
String result = text.replaceAll("^.", replacement);
4
5
System.out.println(result); // xBC
In this example, we remove last character from the original string and add the replacement at the beginning.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC";
5
String replacement = "x";
6
String result = replacement + text.substring(1);
7
8
System.out.println(result); // xBC
9
}
10
}
This approach is equivalent to the above one. Instead of +
operator we concatenate the strings using concat()
method.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC";
5
String replacement = "x";
6
String result = replacement.concat(text.substring(1));
7
8
System.out.println(result); // xBC
9
}
10
}
In this example, we use string replaceAll()
with "^."
regex to replace the first character in the text
string.
Regex explanation:
^
- matches the beginning of the string,.
- matches any character except linebreaks.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC";
5
String replacement = "x";
6
String result = text.replaceAll("^.", replacement);
7
8
System.out.println(result); // xBC
9
}
10
}
Note:
Regular expressions are slower than
substring()
method.