2012-10-30 50 views
-2

我的工作在我的COM的类一个任务,需要我创造的财富游戏的车轮。我目前正在研究getDisplayedPhrase方法,我将解释。因此,对于这个节目,我有例如
"this is a question, thanks for helping!"
随机句话我想这句话改为
"**** ** * ********, ****** *** *******!"
这句话应该怎么看起来像他们想它。正如你所看到的,我想只改变字母,所以我创建了一个代替某些字符的字符串

private static final String alpha ="abcdefghijklmnopqrstuvwxyz" 

,以避免任何标点符号。 这是我到目前为止有:

public String getDisplayedPhrase() { 
    for (int i = 0; i<secretPhrase.length(); i++){ 
     I don't know what to put here and what method to use??? 
       I'm thinking of using charAt() or indexOf() 
    } 
    return displayedPhrase; 
} 
+6

而不是说我不知道​​,拿一个飞跃,并尝试使用的charAt()和的indexOf(),然后会被卡住。 – Arham

回答

3

您可以使用字符类来确定一个字符是字母。

String s = "this is a question, thanks for helping!"; 
      StringBuilder rep=""; 
      for(int i=0; i<s.length();i++){ 
       if(Character.isAlphabetic(s.charAt(i))){ 
        rep.append("*"); 
       } 
       else { 
        rep.append(s.charAt(i)); 
       } 
      } 
      System.out.println(rep); 

您还可以使用String.replace()并替换现有的字符串,而不是额外的新的String的

for(int i=0; i<s.length();i++){ 
      if(Character.isAlphabetic(s.charAt(i))){ 
       s=s.replace(s.charAt(i), '*'); 
      } 

     } 
     System.out.println(s); 

输出:

**** ** * ********, ****** *** *******! 
+0

这就造成数十不必要的临时字符串,使用StringBuilder – jozefg

+0

@jozefg真的,只是它编辑感谢.. :)显示非正则表达式的答案,因为它是什么OP居然问起 – PermGenError

+1

好主意。 :) –

6
return secretPhrase.replaceAll("[a-zA-Z]","*") 
+0

或'\ w'如果0-9也要被转换。 – Adam

+1

为读者练习 - 延伸以应付重音字符 - 'lesdégâtssur laCôteest envidéo'将变成** ** ** ** ** ** ** ** ** ** * *é**'使用'\ w' – DNA

+0

Java正则表达式对本地化的支持很差。 [链接](http://stackoverflow.com/questions/4304928/unicode-equivalents-for-w-and-b-in-java-regular-expressions) –

2
Pattern letterDigitPattern = Pattern.compile([a-zA-Z0-9]); 
public String getDisplayedPhrase() { 
    Matcher m = letterDigitPattern.matcher(secretPhrase); 
    return m.replaceAll("*"); 
} 
+0

这是不必要的冗长,看到Clints回答 – jozefg

+0

它还帮助提问者不必要地了解什么是速记replaceAll,并找到相关的不必要的API文档。哎呀! –

+0

超详细。 downvote – Rezigned