如何用1
替换每个one
,用2
替换每个two
,用3
替换每个three
...
来自输入?
我的代码:
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
String Input = JOptionPane.showInputDialog("Text:");
String Output;
//replace
Output = Input.replaceAll("1", "one");
Output = Input.replaceAll("2", "two");
//Output
System.out.println(Output);
}
}
它只能使用一个替换项。
答案 0 :(得分:5)
您需要第二次致电replaceAll
上的OutPut
:
Output = Input.replaceAll("1", "one");
Output = Output.replaceAll("2", "two");
或只需流畅地致电replaceAll
:
Output = Input.replaceAll("1", "one").replaceAll("2", "two");
答案 1 :(得分:2)
您的代码使用Output
作为源字符串两次设置了Input
。因此,第一次调用Output = Input.replaceAll("2", "two);
会完全无效。
您可以将其替换为:
Output = Input.replaceAll("1", "one");
Output = Output.replaceAll("2", "two");
但是,如果要定义很多替换项,那将有点过分且变得非常麻烦。
HashMap
来存储要替换的值以及替换值。
使用HashMap<Character, String>
可以存储单字符“键”或要替换的值及其替换字符串。
然后,只需读取输入字符串的每个字符并确定HashMap
何时为其定义了替换项。
import java.util.HashMap;
public class Main {
private static HashMap<Character, String> replacementMap = new HashMap<>();
public static void main(String[] args) {
// Build the replacement strings
replacementMap.put('1', "one");
replacementMap.put('2', "two");
replacementMap.put('3', "three");
replacementMap.put('4', "four");
replacementMap.put('5', "five");
replacementMap.put('6', "six");
replacementMap.put('7', "seven");
replacementMap.put('8', "eight");
replacementMap.put('9', "nine");
replacementMap.put('0', "zero");
String input = "This is 1 very long string. It has 3 sentences and 121 characters. Exactly 0 people will verify that count.";
StringBuilder output = new StringBuilder();
for (char c : input.toCharArray()) {
// This character has a replacement defined in the map
if (replacementMap.containsKey(c)) {
// Add the replacement string to the output
output.append(replacementMap.get(c));
} else {
// No replacement found, just add this character to the output
output.append(c);
}
}
System.out.println(output.toString());
}
}
输出:
这是一个很长的字符串。它有三个句子和一个两个字符。完全为零的人将验证此计数。
限制:
首先,此实现取决于所需的功能和范围。由于可能的数目是无限的,所以这不能解决这个问题。
此外,这还会寻找要替换的单个字符。例如,如果要扩展此范围以将“ 10”替换为“十”,则需要使用HashMap<String, String>
。
不幸的是,您最初的问题没有提供足够的背景信息,无法为您建议最佳的方法。