user2722119
user2722119

Reputation: 15

How to replace a 1 or more charceters in string with other characters?

I need to print

......e......                
..e..........                
........e....                


.....iAi.....

where e is and enemy with a position, so i have replace a dot with changing position, with 0 being the center boundaries -6 and 6 on the left and right respectively. and the iAi is the player with 2 gun so i have to replace 3 "." with 2 i and 1 A what i have so far for the enimes is

String asd = ".............";
    char cas;
    if ((isDead()== true)|| (justHit=true))
    cas = 'x';
    else 
    cas ='e';
    String wasd = asd.substring(0,position-1)+cas+asd.substring(position +1);
    return wasd;

but it isn't replacing in the right place

Upvotes: 1

Views: 118

Answers (3)

Andrew Wynham
Andrew Wynham

Reputation: 2398

Use asd.substring(0, position) instead of asd.substring(0, position - 1) in your code above.

Upvotes: 1

jboi
jboi

Reputation: 11912

Using a String means to recreate an amount of Objects in every loop. Using char[] should significantly lower the footprint:

    private char[] afd = {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'};
    private int prevPos = 0;

    public String placeEnemy(int newPos, boolean dead, boolean justHit) {
        afd[prevPos] = '.';
        afd[newPos] = 'e';
        prevPos = newPos;
        return afd
    }

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136142

try this, maybe it will help

    String s1 = ".............";
    String s2 = "xx";
    int p = 1;
    String s3 = s1.substring(0, p)  + s2 + s1.substring(p + s2.length());
    System.out.println(s1);
    System.out.println(s3);

output

.............
.xx..........

Upvotes: 1

Related Questions