Home > Mobile >  Rotating a String with StringBuilder instead of a character array
Rotating a String with StringBuilder instead of a character array

Time:12-29

Aiming to check whether a String is a rotation of another String by rotating it until it matches.

Tried to use a StringBuilder to rotate said String instead of a char[ ] because it is more efficient, but I can't determine why the String is only rotating once, instead of a.length()-1 times.

public static void main(String[] args) {
    
    String a = "erbottlewat";
    String b = "waterbottle";
    
    System.out.println(isSubstring(a,b));
    
}


    public static boolean isSubstring(String a, String b) {
    
    StringBuilder strbdr = new StringBuilder(a); // can pick either string. if one ends up matching the other one, we know it is a rotation
    
    for(int i = 0; i < a.length()-1; i  ) { // this is the number of times the program will run
        
        char temp = a.charAt(0);
        
        for(int j = 0; j < a.length()-1; j  ) {
            strbdr.setCharAt(j, a.charAt(j 1)); // tried to use a stringbuilder because i read it was the most efficient way.
        }
        
        strbdr.setCharAt(a.length()-1, temp);
        
        System.out.println(strbdr.toString());
        
        if(strbdr.toString().equals(b)) {
            return true;
        }
    }
    return false;
    
}

}

CodePudding user response:

My mistake was indexing String a (which never changed) to replace elements with the StringBuilder. By replacing strbdr.setCharAt(j, a.charAt(j 1)); with strbdr.setCharAt(j, strbdr.charAt(j 1));, I was able to save my changes and rotate the string properly.

Solution:

public static void main(String[] args) {
    
    String a = "erbottlewat";
    String b = "waterbottle";
    
    System.out.println(isSubstring(a,b));
    
}

public static boolean isSubstring(String a, String b) {
    
    StringBuilder strbdr = new StringBuilder(a);
    
    for(int i = 0; i < a.length()-1; i  ) {
        
        char temp = strbdr.charAt(0);
        
        for(int j = 0; j < a.length()-1; j  ) {
            strbdr.setCharAt(j, strbdr.charAt(j 1));
        }
        
        strbdr.setCharAt(a.length()-1, temp);
        
        System.out.println(strbdr.toString());
        
        if(strbdr.toString().equals(b)) {
            return true;
        }
    }
    return false;
    
}
  • Related