-7
public class Test1 {

public static void main(String[] args) {
    String s = "ciao";
    String underscore = s.replaceAll(".", "_ ").trim();

    if (s.contains("a")){
        for (int i = 0; i< underscore.length(); i++){



        }
    }
    System.out.println(underscore);
}
}

Hello how to replace the string "a" in the correct posistion of the underscore? I am doing an HangMan game so the algorithm that I have to implement is general not only this case. The problem is that my index of underscore are different and the format is "_ _ _ _" have to be "c i a o" but if I do only one guess so "a".. the output is " _ _ a _"

HKing
  • 83
  • 1
  • 12
  • check out at `charAt(int index)` method. – npinti Apr 09 '15 at 10:33
  • Why should I use this method? – HKing Apr 09 '15 at 10:39
  • You could use it to compare the character at the `ith` location for `s` with what the user has provided. If it is, replace the `ith` character of `underscore` with whatever the user has provided. – npinti Apr 09 '15 at 10:42
  • Maybe is better to do this way: I do an array of the guess word then if not the element in the guess array do _ if there is replace it with the word.. – HKing Apr 09 '15 at 10:51

2 Answers2

4

You should keep a reference of the position of each letter in the string. You can use the toCharArray method.

    String s = "ciao";
    String underscore = s.replaceAll(".", "_ ").trim();
    char[] sC = s.toCharArray();
    if(s.contains("a"){
      StringBuilder myUnderscore = new StringBuilder(underscore);
      for(int i = 0; i < sC.length; i++){
         if(sc[i] == 'a'){
           myUnderscore.setCharAt(i, 'a');
         }
      }
    }
    myUnderscore.toString();

Hope it helps, it's my first answer!

woland
  • 416
  • 3
  • 7
  • it works but String underscore = s.replaceAll(".", " _"); and myUnderscore.setCharAt(2*i+1, 'a'); myUnderscore.toString().trim(); – HKing Apr 09 '15 at 11:31
  • I can't add you a reputation because I have -7 I don't know why lol.. but thank you very much.. – HKing Apr 09 '15 at 11:48
0

Another way, if you don't want to use StringBuilder class:

String s = "ciao";
String underscore = s.replaceAll(".", "_ ").trim();
System.out.println(underscore);

if (s.contains("a")) {
    char[] ca = underscore.toCharArray();
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) != 'a') {
            continue;
        }

        int j = i * 2;
        ca[j] = 'a';
    }

    // one way:
    underscore = String.valueOf(ca);

    // second way:
    // underscore = new String(ca);
}
System.out.println(underscore);

This solution calculates the character positions of s in the character array underscore.

References:

Community
  • 1
  • 1
Christian St.
  • 1,751
  • 2
  • 22
  • 41