我有一个字符串,其中包含某些“令牌” 示例:
"Someone e.g. X here is a # and the other i.e. X is not but over is something else like #"
我还有一个String列表,例如{"John", "doctor", "Jim","engineer"}
执行以下操作的最佳方式是什么:
我想用列表中的相应元素替换所有 #
个字符。
即。我想跳过X
和John
并将Jim
替换为#
,将engineer
替换为其他#
。
我想绕过string#toCharArray()
,但我感兴趣的是有更好的方法来做到这一点。
注意:第二个列表中的值匹配相应的令牌。因此,列表中的第一个值John
映射到X
或#
的第一个出现的地方。
示例:
输入:"Someone e.g. X here is a # and the other i.e. X is not but the other is something else like # but X is at least X but not #"
{"John", "doctor", "Jim","John", "engineer", "doctor"}
输出:
"Someone e.g. X here is a doctor and the other i.e. X is not but the other is something else like Jim but X is at least X but not doctor"
答案 0 :(得分:2)
您可能有兴趣看一下MessageFormat允许类似这种替代的内容。
E.g。
MessageFormat.format(""
+ "Someone e.g. {0} here is a {1} and the other i.e. {2} "
+ "is not but over is something else like {3}",
new String [] {"John", "doctor", "Jim","engineer"});
修改强>:
如果无法修改输入字符串以包含占位符,并且占位符具有您在更新中提到的特殊含义(即应忽略X,应该替换#),那么您只需要
StringBuilder
。StringBuilder
对象。counter
处的值,并将其附加到StringBuilder
对象。StringBuilder.toString()
并修剪以删除尾随空格。