Garry
Garry

Reputation: 107

Replacing characters of a string in a particular sequence

The String word contains a character ] at more than one place. I want to replace any character before the ] by l, and any character after by r.

For example, the String defined below:

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

Should be converted to:

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

When I tried by the following code:

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

It changes the right side of ] by r, but fails left to it by l. I need help to get the required results.

Upvotes: 0

Views: 107

Answers (4)

Rakhi
Rakhi

Reputation: 9

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

Upvotes: 1

deme72
deme72

Reputation: 1153

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

using regex and string methods is useful in this situation

Upvotes: 1

Ajeesh
Ajeesh

Reputation: 41

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

Upvotes: 1

Yazan
Yazan

Reputation: 6082

    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

Upvotes: 1

Related Questions