简体   繁体   English

如何用字符串替换字符?

[英]How do I replace a character with a string?

I need to input a String that contains a single * character, then a second String. 我需要输入一个包含单个*字符的字符串,然后输入第二个String。 The * will be replaced by the second String. *将被第二个字符串替换。 So for example, if the user enters the Strings "d*g" and "in", the program outputs ding. 因此,例如,如果用户输入字符串“ d * g”和“ in”,则程序将输出ding。 The original String must contain only letters of the alphabet, capital or lowercase, spaces and tab, and a single *. 原始字符串必须仅包含字母,大写或小写字母,空格和制表符以及单个*。 The replacement String may be any legal String in Java. 替换字符串可以是Java中的任何合法字符串。 If the first String does not contain a * “Error: no *“ should be output. 如果第一个字符串不包含*,则输出“错误:否*”。 If the first String contains anything other than letters of the alphabet, spaces or tabs then “Error: Incorrect characters“ should be printed. 如果第一个字符串包含字母,空格或制表符之外的任何内容,则应打印“错误:不正确的字符”。 If the first String does not have a * I do not have to check for incorrect characters, only “Error: no *“ should be output. 如果第一个字符串没有*,则不必输出不正确的字符,则仅输出“错误:否*”。

What I have so far: 到目前为止,我有:

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);







}

}
}

I believe you wanted String.replace(CharSequence, CharSequence) (not replaceAll that takes a regular expression). 我相信您想要String.replace(CharSequence, CharSequence) (而不是需要正则表达式的replaceAll )。

String my_new_str = wc.replaceAll("*", replace);

should be 应该

String my_new_str = wc.replace("*", replace);

You can test it like 您可以像测试

String wc = "d*g";
String replace = "in";
System.out.println(wc.replace("*", replace));

And get (as requested) 并获取(按要求)

ding

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM