Languages
[Edit]
EN

Java - replace first character in string

0 points
Created by:
Zachariah
298

In this article, we would like to show you how to replace the first character in string in Java.

Quick solution:

or:

or:

 

1. Practical example using String substring()

Edit

1.1 With + operator

Edit

In this example, we remove last character from the original string and add the replacement at the beginning.

1.2 With concat() method

Edit

This approach is equivalent to the above one. Instead of + operator we concatenate the strings using concat() method.

2. Practical example using String replaceAll() with regex pattern

Edit

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.

Note:

Regular expressions are slower than substring() method. 

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String (popular problems)

Java - replace first character in string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join