Java – Shifting characters in a string to the left

java

I'm new to Stack Overflow and I have a lab question for a programming class that's been eluding me. The problem requires us to shift the elements of a string s to the left k times. For instance, if the input is "Hello World" and 3, it would output "lo WorldHel"). It also has to work relatively efficiently for very large values of k. This is what I have so far:

 String cyclicLeftShift(String s, int k){
   String result="";  

   for(int i=0;i<k;i++){
       result = s.substring(1, s.length() - 1) +s.charAt(0);

       s=result;
    }
    return s;
}

My major issue is that the last character of the original string keeps getting overwritten by the subsequent iterations of the loop. I've tried a great number of permutations, including converting the whole thing to arrays (which violates the efficiency restriction in the original problem). I feel like there's just a tiny thing I'm not getting, and I was wondering if someone could give me a nudge in the right direction?

Thank you!

Best Answer

What you want is to split the string at position k and merge both parts together again but in reverse order. The main problem is that k may be greater than or equal to the size of your string. So you need to bring k into a valid range again.

public static String cyclicLeftShift(String s, int k){
    k = k%s.length();
    return s.substring(k) + s.substring(0, k);
}

Testing the method:

public static void main(String[] args)
{
    String test = "Hello World";
    for(int i = 0; i < test.length()*3; i++)
        System.out.println(cyclicLeftShift(test, i));
}

Output:

Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
 WorldHello
WorldHello 
orldHello W
rldHello Wo
ldHello Wor
dHello Worl
Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
 WorldHello
WorldHello 
orldHello W
rldHello Wo
ldHello Wor
dHello Worl
Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
 WorldHello
WorldHello 
orldHello W
rldHello Wo
ldHello Wor
dHello Worl