Java – moves characters in a string to the left
I'm a novice at stack overflow. I have a lab problem with a programming class that has been avoiding me The problem requires us to move the element of string s to the left K times For example, if the inputs are "Hello world" and 3, "Hello world" is output For very large K values, it must also work relatively efficiently This is what I have done 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 main problem is that the last character of the original string is constantly overwritten by subsequent iterations of the loop I've tried a lot of permutations, including converting the whole thing into an array (which violates the efficiency limit in the original problem) I think there's a little thing I didn't get. I wonder if anyone can give me a push in the right direction?
thank you!
Solution
What you want is to split the string at position K and merge the two parts together again, but in the opposite order
public static String cyclicLeftShift(String s,int k){ k = k%s.length(); return s.substring(k) + s.substring(0,k); }
Test 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