在Java中,当用户输入短语和要替换的字符时,如何替换字符?

时间:2014-09-11 03:33:38

标签: replace character mutation

我正在尝试用Java创建代码,用户在其中创建(输入)一个短语,然后选择(输入)一个字符。 从那里我想要接受用户输入并将他们选择的角色替换为他们创建的短语中的X.我不完全确定如何创建它,我知道我想使用Scanner然后我不知道我是否必须创建一个新字符串或使用变异方法。运行时假设看起来像这样:

  • 输入短语:Pizza很好
  • 输入字符:z
  • Pixxa很好郎

我对Java很新,这是我到目前为止所尝试的内容

这是我的代码:

import java.util.Scanner;
public class ModifyStrings 
{ 
public static void main (String[] args)
{
String enterPhrase;
    String enterCharacter;

    //Scanner
    Scanner scan2 = new Scanner (System.in);

    //Print out that the user will see and type in
    System.out.println("Enter a phrase or sentence: ");
            enterPhrase = scan.nextLine();

    //Second print out that the user will enter in for a character to change
    System.out.println("Enter Character: ");
    enterCharacter = scan.nextLine();

    //mutation
            ?

    //Character changes that letter into x
    System.out.println("New phrase: "+ enterPhrase);
  }
}

谢谢!

1 个答案:

答案 0 :(得分:2)

这可以通过使用String方法replaceAll()来完成。尝试下面的代码,这将适合你。

import java.util.Scanner;

public class ModifyStrings { 

    public static void main (String[] args) {   

        String enterPhrase;
        String enterCharacter;

        //Scanner
        Scanner scan = new Scanner (System.in);

        //Print out that the user will see and type in
        System.out.println("Enter a phrase or sentence: ");
                enterPhrase = scan.nextLine();

        //Second print out that the user will enter in for a character to change
        System.out.println("Enter Character: ");

        // This line of code firstly get the string truncate white spaces and then get the first character not all
        enterCharacter =  scan.nextLine().trim().substring(0, 1);

        //Mutation code replace x with your desired character do you want to replaces
        enterPhrase =  enterPhrase.replaceAll(enterCharacter, "x");


        //Character changes that letter into x
        System.out.println("New phrase: "+ enterPhrase);
 }
}