duncdudeable
duncdudeable

Reputation: 11

StringBuilder Checking for lettervalues

I'm trying to change all letters in StringBuilder to hyphens and leave all non letter values alone(such as spaces apostrophes etc), how could I do that without listing and comparing all letters, is that even possible

private StringBuilder puzzle = new StringBuilder("I'm the cat")
for (int i = 0; i < guess.length(); i++) {
    if (puzzle.charAt(i) == ' '){ 
       puzzle.setCharAt(i, ' ');     }
    else 
       puzzle.setCharAt(i, '-');
     } 

So output would be something like ( -'- --- ---)

Upvotes: 1

Views: 32

Answers (2)

moarCoffee
moarCoffee

Reputation: 1319

This should do the trick:

import java.util.regex.Pattern;

.
.
.

Pattern p = Pattern.compile("\\w");

String s = p.matcher("I'm the cat").replaceAll("-");

System.out.println(s);  // prints "-'- --- ---"

You can use <string>.replaceAll("\\w", "-") as well, but if you're going to be doing lots of replacements in a method, then it's technically more efficient to compile the Pattern in advance (although admittedly not by very much in this situation).

Upvotes: 1

user2575725
user2575725

Reputation:

Try replaceAll():

System.out.println("I'm the cat".replaceAll("\\w", "-")); //prints: -'- --- ---

Upvotes: 1

Related Questions