I have a string like :
string = abcdefghabcd
Now lets say I want to replace the first occurrence of a
. I tried something like this :
string[string.indexOf('a')] = '0'
But this doesn't seems to be working. Any other way I can do this?
Thanks in advance.
In Java you can use String.replaceFirst() :
String s = "abcdefghabcd";
s = s.replaceFirst("a", "0");
System.out.println(s);
Output will be :
0bcdefghabcd
Warning : the replaceFirst()
method takes a regex : so if you want to replace a special character like [
you need to escape by putting a \
before it. \
being a special character itself, you need to double it as follow :
s = s.replaceFirst("\\[", "0");
Here is the documentation on Java Regular Expressions. Also, here is Oracle's Java tutorial on manipulating Characters in Strings.
You should be aware that strings in Java are immutable. They cannot be changed. Any method you use to "change" a string will have to return a new string. If you want to modify a string directly you will need to use a mutable string type like StringBuilder.
There are many methods in the String API docs that will help you get a modified version of your string, including s.replace(), s.replaceAll(),s.replaceFirst(), ... or you could use a combination of substring and "+" to create a new string.
If you really want to treat the string as an array as in your initial example, you could use String.getChars to get an array of characters, manipulate that, and then use the String constructor String(char[]) to convert back to a String object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With