Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace in Array

Tags:

java

im trying make one replace in string from a array but this dont work

dna[i].replace('T', 'C');

and with this way work?

"ATCTA".replace('T', 'C');

why dont work with array, how i can use use a replace in array[]

Now i have other problem, i want use various replaces in original string, how i can mahe this????

like image 474
Mac135 Avatar asked Dec 23 '22 01:12

Mac135


2 Answers

 String dna[] = {"ATCTA"};
 int i = 0;
 dna[i] = dna[i].replace('T', 'C');
 System.out.println(dna[i]);

This works as expected. Double check your code if you follow a similiar pattern.


You may have expected, that dna[i].replace('T', 'C'); changes the content of the cell dna[i] directly. This is not the case, the String will not be changed, replace will return a new String where the char has been replaced. It's necessary to assign the result of the replace operation to a variable.


To answer your last comment:

Strings are immutable - you can't change a single char inside a String object. All operations on Strings (substring, replace, '+', ...) always create new Strings.

A way to make more than one replace is like this:

dna[i] = dna[i].replace('T', 'C').replace('A', 'S');
like image 133
Andreas Dolk Avatar answered Jan 09 '23 15:01

Andreas Dolk


An array is just a data structure that holds data. It doesn't support any operations on that data. You need to write the algorithms to work on the data yourself.

A String is basically a char array with some methods that you can call on that. The replace() method is one of them.

The method you want would look something like this:

static void replace(char[] arr, char find, char replace) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == find) {
            arr[i] = replace;
            return;
        }
    }
}

You would then call it like so:

replace(dna, 'T', 'C');

That would replace the first instance of T in the array with a C.

like image 20
jjnguy Avatar answered Jan 09 '23 17:01

jjnguy