如何根据另一个字符串的未知长度创建一个新的String?

时间:2014-11-24 03:04:54

标签: java string substring

我目前正处于一个计算机编程课程中并且处于一个死胡同,以便创建一个模板"这个2人吊人游戏。

  • 首先,提示人#1提供短语(包含全部小写)
  • 然后,我必须接受他们选择的任何短语,并将其变成一个包含所有短语的模板。
  • 然后,当第2个人猜出字母时,我必须"显示"这句话并且将其变成了短语。

我无法将其转换为模板。一个例子是:

#p>第一个人的短语:" hello world"

所需的模板结果:" ????? ?????"

这就是我到目前为止......我在公共静态字符串中遇到了麻烦String createTemplate(String sPhrase)

    import java.util.Scanner;

public class Program9 
{
public static void main (String[] args)
{
    Scanner scanner = new Scanner (System.in);
    Scanner stdIn = new Scanner (System.in);

    int cnt = 0; //counter is set to zero
    String sPhrase;
    boolean def;

    System.out.print("Enter a phrase consisting of only lowercase letters and spaces: ");
    sPhrase = scanner.nextLine(); //reads into variable set to Scanner.nextLine()


    System.out.println("\n\n\nCommon Phrase");
        System.out.println("--------------\n");

        String template = createTemplate(sPhrase); //will run through "createTemplate" and show whatever on there.

    do
    {

        char guess = getGuess(stdIn); //will run through "getGuess" and show whatever SOP and return from that. WORKS.

        cnt = cnt + 1; //counts the guess

        System.out.println("\n\n\nCommon Phrase");
        System.out.println("--------------\n");

        String updated = updateTemplate(template, sPhrase, guess); //runs throuhgh and prints updated template




    } while (!exposedTemplate(sPhrase)); //will loop back if updated template still has ?'s



    System.out.println("Good job! It took you " + cnt + " guesses!");
}
public static String createTemplate(String sPhrase)
{
    String template = null;
    String str;


    sPhrase.substring(0, sPhrase.length()+1); //not sure if +1 needed.
    sPhrase.equals(template);

    //THIS IS WHERE IM HAVING PROBLEMS



}
public static char getGuess(Scanner stdIn)
{
    //repeatedly prompts user for char response in range of 'a' to 'z'
    String guess;

    do
    {
        System.out.print("Enter a lowercase letter guess : ");
        guess = stdIn.next();
    } while (Character.isDigit(guess.charAt(0)));

    char firstLetter = guess.charAt(0);
    return firstLetter;
}

public static String changeCharAt(String str, int ind, char newChar)
{
    return str.substring(0, ind) + newChar + str.substring(ind+1);
    //freebie: returns copy of str with chars replaced

}
public static String updateTemplate(String template, String sPhrase, char guess)
{
    //will have to include changeCharAt


}
public static boolean exposedTemplate(String template)
{
    // returns true exactly when there are no more ?'s

}
}

3 个答案:

答案 0 :(得分:3)

一个简单的解决方案是:

public static String createTemplate(String sPhrase)
{
    return sPhrase.replaceAll("[a-zA-Z]", "?");
}

Java中String classreplaceAll方法将字符串中与提供的正则表达式匹配的所有部分替换为字符串(在本例中为?

学习正则表达式(称为正则表达式)可能不在此作业范围内,但对于所有计算机程序员来说都是非常有用的技能。在这个例子中,我使用了正则表达式[a-zA-Z],这意味着替换任何大写或小写字符,但是你也可以使用像\\w这样的字符类。

这里有一个关于Java正则表达式的优秀教程:https://docs.oracle.com/javase/tutorial/essential/regex/

答案 1 :(得分:2)

您需要for-loop,您需要检查短语的每个字符,String#charAt应该有所帮助。如果角色不是空格,您可以在模板上附加?,否则您需要附加空格......

有关详细信息,请参阅The for Statement ...

StringBuilder sb = new StringBuilder(sPhrase.length());
for (int index = 0; index < sPhrase.length(); index++) {
    if (sPhrase.charAt(index) != ' ') {
        sb.append("?");
    } else {
        sb.append(" ");
    }
}
sTemplate = sb.toString();

同样可以使用......

StringBuilder sb = new StringBuilder(sPhrase.length());
for (char c : sPhrase.toCharArray()) {
    if (c != ' ')) {
        sb.append("?");
    } else {
        sb.append(" ");
    }
}
sTemplate = sb.toString();

但我认为第一个会更容易理解......

答案 2 :(得分:-1)

只需使用正则表达式和String.replaceAll()方法:

public static String createTemplate(String sPhrase)
{
    return sPhrase.replaceAll(".", "?");
}

在这个例子中,第一个参数是正则表达式,所以“。”匹配所有字符。第二个参数是用“?”替换所有正则表达式匹配的字符串。

相关问题