2013-09-22 141 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)在你的代碼之上。

相關問題