更新时间:2023-12-05 13:08:28
除非你非常渴望表现,否则我会采用一种非常简单的方法:
Unless you're absolutely desperate for performance, I'd use a very simple approach:
String result = input.replace("*", "asterisk")
.replace("%", "percentage")
.replace("@", "at"); // Add more to taste :)
(请注意,替换
和 replaceAll
- 后者采用正则表达式。很容易得到错误的并看到截然不同的效果!)
(Note that there's a big difference between replace
and replaceAll
- the latter takes a regular expression. It's easy to get the wrong one and see radically different effects!)
另一种选择是:
public static String replaceSpecial(String input)
{
// Output will be at least as long as input
StringBuilder builder = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
switch (c)
{
case '*': builder.append("asterisk"); break;
case '%': builder.append("percentage"); break;
case '@': builder.append("at"); break;
default: builder.append(c); break;
}
}
return builder.toString();