【发布时间】:2015-11-04 04:14:32
【问题描述】:
我需要输入一个包含单个 * 字符的字符串,然后是第二个字符串。 * 将被第二个字符串替换。例如,如果用户输入字符串“d*g”和“in”,程序会输出 ding。 原始字符串必须仅包含字母、大写或小写字母、空格和制表符以及单个 *。替换字符串可以是 Java 中的任何合法字符串。 如果第一个字符串不包含 *“Error: no *”,则应输出。 如果第一个字符串包含字母、空格或制表符以外的任何内容,则应打印“错误:不正确的字符”。如果第一个字符串没有 * 我不必检查不正确的字符,应该只输出“Error: no *”。
到目前为止我所拥有的:
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;
class Main{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
char letter;
int i;
System.out.println("Enter the first String:");
String wc = scan.nextLine();
System.out.println("Enter the replacement String:");
String replace = scan.nextLine();
String my_new_str = wc.replaceAll("*", replace);
for (i = 0; i < wc.length(); i++)
{
letter = wc.charAt(i);
if (! (letter == '*')){
System.out.println("Error: no *");}
System.out.println(""+ my_new_str);
}
}
}
【问题讨论】:
-
因为
*是一个特殊的元字符,你需要像String my_new_str = wc.replaceAll("\\*", replace);一样转义*