Java 在数组中替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3250405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace in Array
提问by Mac135
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????
现在我有其他问题,我想在原始字符串中使用各种替换,我该怎么办????
采纳答案by Andreas Dolk
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.
您可能已经预料到,这dna[i].replace('T', 'C');
会dna[i]
直接更改单元格的内容。情况并非如此,字符串不会改变,replace
将返回一个新的字符串,其中字符已被替换。有必要将replace
操作的结果分配给一个变量。
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.
字符串是不可变的 - 您不能更改 String 对象内的单个字符。对字符串的所有操作(子字符串、替换、'+'、...)总是创建新的字符串。
A way to make more than one replace is like this:
一种进行多次替换的方法是这样的:
dna[i] = dna[i].replace('T', 'C').replace('A', 'S');
回答by jjnguy
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.
AString
基本上是一个 char 数组,其中包含一些您可以调用的方法。该replace()
方法是其中之一。
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
.
这将用 a 替换T
数组中的第一个实例C
。