2013-09-22 143 views
1

我需要打印如何用其他字符替换字符串中的一个或多个charceters?

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


.....iAi..... 

其中e是和与位置的敌人,所以我有不断变化的位置,0为中心的边界-6和6上的左和右分别替换一个点。而iAi是拥有2支枪的玩家,所以我必须替换3个“。”与2个和1个一 什么我迄今为止的enimes是

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; 

但它不是在正确的地方更换

+2

第一件事首先'(justHit = true)'应该是'(justHit == true)' – Prateek

+4

@Prateek,更好,但是简单'justHit'。 – zch

+0

是的,但我想指出他的错字 – Prateek

回答

1

试试这个,也许这将有助于

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); 

输出

............. 
.xx.......... 
+0

玩家“iAi” – user2722119

1

使用字符串表示在每个循环中重新创建一定数量的对象。使用char []应该显著降低足迹:

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 
    } 
1

使用asd.substring(0, position)而不是asd.substring(0, position - 1)在你的代码之上。

相关问题