在Java中,我拿到一个字符串,我需要把这个字符串中的英文标点换成中文的,该怎么写
时间: 2024-02-27 17:58:25 浏览: 21
你可以先定义一个包含所有需要转换的英文标点和相应中文标点的 Map,然后遍历这个 Map,将字符串中的所有对应的英文标点替换成对应的中文标点。具体代码如下所示:
```java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String str = "Hello, world! This is a test.";
// 定义英文标点和中文标点的对应关系
Map<String, String> punctuations = new HashMap<>();
punctuations.put(",", ",");
punctuations.put(".", "。");
punctuations.put("!", "!");
punctuations.put("?", "?");
punctuations.put(":", ":");
punctuations.put(";", ";");
punctuations.put("(", "(");
punctuations.put(")", ")");
// 遍历 Map,将字符串中的英文标点替换成中文标点
for (Map.Entry<String, String> entry : punctuations.entrySet()) {
String enPunc = entry.getKey();
String cnPunc = entry.getValue();
str = str.replace(enPunc, cnPunc);
}
System.out.println(str); // 输出:Hello, world! This is a test。
}
}
```
在上面的代码中,我们定义了一个包含所有需要转换的英文标点和相应中文标点的 Map,然后遍历这个 Map,将字符串中的所有对应的英文标点替换成对应的中文标点。最后输出转换后的字符串。