Search code examples
javareplaceall

ReplaceAll not working on String[] element


I need to write chess programm that uses FEN as an argument for creating a chess board. To simplyfy the process I want to replace number with equal amount of "1" to that number with replaceAll method (look my code). Unfortunately this doesn't work and I don't know know why. Can somebody please tell me what I should do differently?

String[] read2 = new String[] {"rnbqkbnr", "pppppppp", "8", "8", "8", "8", "PPPPPPPP", "RNBQKBNR"};         
for (int i = 0; i < 8; i++ ) {
    System.out.println(read2[i]);
    read2[i].replaceAll("8", "11111111");
    read2[i].replaceAll("7", "1111111");
    read2[i].replaceAll("6", "111111");
    read2[i].replaceAll("5", "11111");
    read2[i].replaceAll("4", "1111");
    read2[i].replaceAll("3", "111");
    read2[i].replaceAll("2", "11");
    System.out.println(read2[i]);   
}

The output is

rnbqkbnr
rnbqkbnr
pppppppp
pppppppp
8
8
8
8
8
8
8
8
PPPPPPPP
PPPPPPPP
RNBQKBNR
RNBQKBNR

but should be

rnbqkbnr
rnbqkbnr
pppppppp
pppppppp
8
11111111
8
11111111
8
11111111
8
11111111
PPPPPPPP
PPPPPPPP
RNBQKBNR
RNBQKBNR

Solution

  • You need to save results in your array to replace old value with new value, you are generating a new string by calling the replace on the existing string and you are not assigning the new string to the object reference.

     String[] read2 = new String[] {"rnbqkbnr", "pppppppp", "8", "8", "8", "8", "PPPPPPPP", "RNBQKBNR"};
    
    for (int i = 0; i < 8; i++ ) {
    
        System.out.println(read2[i]);
        read2[i] = read2[i].replace("8", "11111111");
        read2[i] = read2[i].replace("7", "1111111");
        read2[i] = read2[i].replace("6", "111111");
        read2[i] = read2[i].replace("5", "11111");
        read2[i] = read2[i].replace("4", "1111");
        read2[i] = read2[i].replace("3", "111");
        read2[i] = read2[i].replace("2", "11");
        System.out.println(read2[i]);
    
    }
    

    Edit: As suggested in the comments use replace instead of replaceAll because replaceAll is used for Regular expressions.