Replace in Array
im trying make one replace in string from a array but this dont work
dna[i].replace('T', 'C');
and with thi开发者_运维技巧s 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????
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');
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
.
精彩评论