問題描述
我正在編寫一個小的 JAVA 程序:
I'm writing a small JAVA program which:
- 將文本作為字符串
- 需要 2 個字符數組
我嘗試做的事情聽起來像是查找和替換",但它不一樣,所以我認為清除它很重要.
What im trying to do will sound like "find and replace" but it is not the same so i thought its important to clear it.
無論如何,我想獲取此文本,查找第一個數組中的任何字符是否與文本中的字符匹配,如果是,則將其替換為第二個字符數組中的匹配字符(根據索引).
Anyway I want to take this text, find if any char from the first array match a char in the text and if so, replace it with the matching char (according to index) from the second char array.
我會用一個例子來解釋:假設我的文本(字符串)是:java 很棒!";我有 2 個數組(char[]):absm"和!@*$".
I'll explain with an example: lets say my text (String) is: "java is awesome!"; i have 2 arrays (char[]): "absm" and "!@*$".
希望的結果是將 'a' 更改為 '!', 'b' 到 '@' 等等..意味著結果文本將是:
The wished result is to change 'a' to '!' , 'b' to '@' and so on.. meaning the resulted text will be:
java 太棒了!"改為 -> "j i* @w*o$e!"
最有效的方法是什么?為什么?我想過循環文本,但后來發現效率不高.
What is the most efficient way of doing this and why? I thought about looping the text, but then i found it not so efficient.
(StringBuilder/可以使用String類)
(StringBuilder/String class can be used)
推薦答案
StringBuilder sb = new StringBuilder(text);
for(int i = 0; i<text.length(); i ++)
{
for (int j = 0; j < firstCharArray.length;j++)
{
if (sb.charAt(i) == firstCharArray[j])
{
sb.setCharAt(i, secondCharArray[j]);
break;
}
}
}
這種方式很有效,因為它使用 StringBuilder 來更改字符(如果您使用字符串,則每次都必須創建新的,因為它們是不可變的.)而且它還最大限度地減少了您必須執行的傳遞次數(1 傳遞文本字符串,n 傳遞第一個數組,其中 n = text.length())
This way is efficient because it uses a StringBuilder to change the characters in place (if you used Strings you would have to create new ones each time because they are immutable.) Also it minimizes the amount of passes you have to do (1 pass through the text string and n passes through the first array where n = text.length())
這篇關于替換字符串中的字符的有效方法(java)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!