替换特定序列中字符串的字符

时间:2014-05-22 18:14:43

标签: java string

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会向左侧移动。我需要帮助才能获得所需的结果。

4 个答案:

答案 0 :(得分:1)

    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

答案 1 :(得分:1)

 String word="S]RG-M]P";
 word.replaceAll(".]." , "l]r");

使用正则表达式和字符串方法在这种情况下很有用

答案 2 :(得分:1)

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

答案 3 :(得分:1)

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