无法正确替换另一个特定字母

我有一个字符串,我想用另一个字符重复特定的字母,我有一个json响应,其中包含用哪个字母替换的字母。

例如,我的字符串是’abh f’和Json from和to将是 – a => bf,b => 423_,h => 2Re,f => ab

这是问题,当替换时,它将首先替换为bf,然后它将替换ab中的b和转换为a(bf)中的b,这将破坏整个想法,我无法带来好处想法,我已经尝试循环抛出字符串中的每个字母但我无法循环抛出json而没有得到OutOfMemory。

有任何想法吗? 这是代码

for (int i = 0; i < m_jArry.length(); i++) { JSONObject jo_inside = m_jArry.getJSONObject(i); String Original = jo_inside.getString("from"); String To = jo_inside.getString("to"); NewText = NewText.replace(" ","$"); NewText = NewText.replace(Original ,To); } 

您可以先用标记替换每个输入字符串,例如{i} ,其中i是输入的索引,然后用相应索引的输出字符串替换每个标记。

您只需确保令牌不包含在原始字符串中,也不包含在输入/输出中。

然而,这更容易但效率很低。 最好的方法是使用for per char迭代字符串,然后手动执行替换,即:

 String input = /* param of your method */; Map replacements = new HashMap<>(); // Fill map in, like replacements.put('a', "bf"); // Parsing the json every time could be time consuming. // The best structure here is a HashMap. // So I'd suggest that you first create it from the json and then use it whenever. String output = ""; for (char c : input.toCharArray()) { if (map.containsKey(c)) { output += map.get(c); } else { output += c; } } return output; // the result is here 

我认为这取决于您希望更换动作发生的次数。

如果只有一次,那很容易。您可以拆分原始字符串并对每个字符执行替换操作并最终合并结果。

但是如果你允许json中每个令牌的替换操作发生一次以上,我认为当你得到这样的json时,没有OOM就没有办法解决问题了:

{a => b,b => a}

这是第一次回答这个问题,我希望答案对你有用。我想我们可以逐个替换这封信,但不能改变初始输入。这是我的代码。

 String input = "abhf"; StringBuffer result = new StringBuffer(); for(int i = 0;i < input.length();i++) { char value = input.charAt(i); switch(value) { case 'a': result.append("bf"); break; case 'b': result.append("423"); break; case 'h': result.append("2Re"); break; case 'f': result.append("ab"); break; default: result.append(value); break; } } System.out.println(result.toString());