Rotate string left

There is a shift instruction in assembly language called Rotate Left (ROL), and now there is a simple task to simulate the operation result of this instruction with a string. For a given character sequence S, please output the sequence after it is cyclically shifted to the left by K bits. For example, the character sequence S=”abcXYZdef” requires the output of the result of cyclic left shift by 3 bits, that is, “XYZdefabc”. Is not it simple? OK, get it done!


String=>char[] str.toCharArray();
String<=char[] String.valueOf(char[])

package HWday01;

import org.junit.Test;

public class HW04 {
    public String LeftRotateString(String str,int n){
        if(str.length()==0 ){
            return "";
        }
        if(n==0){
            return str;
        }
        char[] ch=str.toCharArray();
        char [] newCh=new char[ch.length];
        for(int i=0;i<n;i++){
            for(int j=0;j<ch.length-1;j++){
                newCh[j]=ch[j+1];
            }
            newCh[ch.length-1]=ch[0];
            for(int j=0;j<newCh.length;j++){
                ch[j]=newCh[j];
            }
        }
        String newStr=String.valueOf(newCh);
        return  newStr;
    }

    @Test
    public void  run1(){
        String a=LeftRotateString("sdadada",3);
        System.out.println("dads");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325169072&siteId=291194637