簡體   English   中英

以特定順序替換字符串的字符

[英]Replacing characters of a string in a particular sequence

String word在多個位置包含一個字符] 我想用l替換]之前的任何字符,並用r替換任何字符。

例如,下面定義的String

String word="S]RG-M]P";

應轉換為:

String word="l]rG-l]r";

當我嘗試以下代碼時:

String word="S]RG-M]P";
char[] a = word.toCharArray();

for(int i=0; i<a.length; i++){
    if (a[i]==']'){
        a[i+1]='r';
        a[i-1]='l';
    }
}

它用r改變]的右側,但是用l改變它的左側。 我需要幫助才能獲得所需的結果。

    public static void main(String[] args) {
    String word = "S]RG-M]P";

    char[] a = word.toCharArray();
    for (int i = 1; i < a.length-1; i++) {//@Jon Skeet again is right X2 :)

        //no need now, for loop bound changed
        //if(i+1>a.length){
    //      continue;
    //  }


        if (a[i] == ']') {

            //no need now, for loop bound changed
            //@Jon Skeet you are right, this handles the case :)
            //if(i==0 || i == a.length-1){
                //continue;
            //}

            a[i + 1] = 'r';
            a[i - 1] = 'l';
        }
    }

    String outt = new String(a);
    System.out.print(outt);
}// main
 String word="S]RG-M]P";
 word.replaceAll(".]." , "l]r");

在這種情況下,使用正則表達式和字符串方法非常有用

StringBuilder word = new StringBuilder("S]RG-M]P");
int index = word.indexOf("]");
while(index > 0){
    word.setCharAt(index-1, 'l');
    word.setCharAt(index+1, 'r');
    index = word.indexOf("]", index+1);
}
System.out.println(word);
for(int i=0 ; i<word.length();i++){  
    char  a =  word.charAt(i);
    String after =null;
    if( Character.toString(a).equals("]")){
        int j = i-1;
        int k = i+1;
        char b =   word.charAt(j);
        char c =   word.charAt(k);
        modifyword= word.replace( Character.valueOf(b).toString(), "l");
        after=  modifyword.replace( Character.valueOf(c).toString(), "r");
        word = after;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM