Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do Insert a char in string (java/groovy)?

Tags:

java

groovy

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.

like image 385
batman Avatar asked Dec 27 '22 19:12

batman


2 Answers

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.

like image 120
Autar Avatar answered Jan 10 '23 03:01

Autar


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.

like image 30
nairbv Avatar answered Jan 10 '23 03:01

nairbv