简体   繁体   中英

How do I replace more than one char in StringBuilder in Java?

I've got some String, and I'd like to replace some chars in it. Everything was running fine until the String hasn't two or more same chars, the program just replacing the first one, and I'm not able to change the second one.

StringBuilder userTitleBuilder = new StringBuilder(conversedTitle); 

    while (score>1) {
        userLetter = userInput.next().charAt(0);
        if (movieTitle.contains(String.valueOf(userLetter))) {
            charIndex = movieTitle.indexOf(userLetter);
            userTitleBuilder.replace(charIndex,userTitleBuilder.length(), String.valueOf(userLetter));
            System.out.println(userTitleBuilder);
        } else {
            --score;
            System.out.println("Wrong\nTries left "+score);
        }
    }

Here's the explanation of this code: User from the start the program has a score equals to 10. userLetter it's just a char that will get some letter from the user, then if statement checking if movieTitle variable has char equals to that user just entered, if yes, charIndex will have it position (but it contains only first index, what if in word are more same letters?) now userTitleBuilder replace the chars in string that has that many "_" that movieTitle lenght, it's just covering the title.

*movieTitle and userTitleBuilder has the same value = "CocaCola" I'd like to not get ready solution. I'd like to have some kind of hint, how do I replace more than one same character in String

A method called String.replace("old","new") can be used. Follow this doc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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