Michelle Schroeder
Michelle Schroeder

Reputation: 23

How do I make a new String based on another string's unknown length?

I am currently in a computer programming class and at a dead end for "creating a template" for this 2-person hang man game.

I can't get past turning it into the template though. An example is:

person#1's phrase: "hello world"

desired template outcome: "????? ?????"

This is what I have so far... I'm having trouble at public static 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

}
}

Upvotes: 2

Views: 197

Answers (3)

Matt Coubrough
Matt Coubrough

Reputation: 3829

A simple solution would be:

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

the replaceAll method of the String class in Java replaces all parts of the string that match the supplied regular expression with a string (in this case ?)

Learning regular expressions (known as regexes) may not be in the scope of this assignment, but is a very useful skill for all computer programmers. In this example I've used the regular expression [a-zA-Z] which means replace any upper or lower case character, however you could also use a character class like \\w.

There is an excellent tutorial on Java regexes here: https://docs.oracle.com/javase/tutorial/essential/regex/

Upvotes: 4

CharlieS
CharlieS

Reputation: 1452

Just use a regex and String.replaceAll() method:

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

In this example, the first parameter is a regex, so "." matches all characters. The second parameter is the string to replace all regex matches with, a "?".

Upvotes: -1

MadProgrammer
MadProgrammer

Reputation: 347314

You'll need a for-loop, you'll need to check each character of the phrase, String#charAt should help. If the character is not a space, you would append an ? to the template, otherwise you'll need to append a space...

See The for Statement for more details...

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

Equally you could use...

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

But I thought the first one would be easier to understand...

Upvotes: 2

Related Questions