-1

I need to replace values in a string:

public static String replaceVals(String str) {
  String[] array = str.split("");
  String newStr = "";
  for (int i = 0; i < array.length; i++) {
    newStr += (array[i] == "T") ? "F" : "T";
  }
  return newStr;
}

Failed results:

input:           "TFF"
expected output: "FTT"
actual output:   "FFF"
O P
  • 2,327
  • 10
  • 40
  • 73

3 Answers3

1

I would just convert your given String to a char array, modify the array, and return a new String using the modified char array.

public static String replaceVals(String str) {
    String[] array = str.toCharArray();
    for (int i=0; i<array.length;i++) {
        array[i] = array[i] == 'T' ? 'F' : 'T';
    }
    return new String(array);
}
eighthrazz
  • 331
  • 1
  • 6
0

you should use .equals instead of ==

== checks for the reference where as.equals checks for value

public static String replaceVals(String str) {
  String[] array = str.split("");
  String newStr = "";
  for (int i = 0; i < array.length; i++) {
    newStr += (array[i].equals( "T")) ? "F" : "T";
  }
  return newStr;
}
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

You can use == when comparing chars so instead of splitting into an array of Strings you can use String.toCharArray to get an array of Characters. Then when you compare you need to use the single quote to create a char.

public static String replaceVals(String str) {
    char[] array = str.toCharArray();
    String newStr = "";
    for (int i = 0; i < array.length; i++) {
      newStr += (array[i] == 'T') ? "F" : "T";
    }
    return newStr;
}
blue
  • 539
  • 3
  • 7