Offer to prove safety forty-three: string left rotation

Casual working

There is a shift in the assembly language instruction called a rotate left (the ROL), and now there is a simple task, this instruction is simulated by the string operation result. For a given character sequence S, you put its left circle after K-bit serial output. For example, the character sequence S = "abcXYZdef", rotated left required output result after three, i.e. "XYZdefabc". Is not it simple? OK, get it!

Thinking

  1. Loop first the number of bits may be more than the given length of the string, the first modulo operation.
  2. Brothers with variable characteristics of StringBuilder String performs append operation.

Code

    public String LeftRotateString(String str,int n) {
        int len=str.length();
        if(len==0) return "";
        int w=n%len;
        if(w==len) return str;
        char [] chars=str.toCharArray();
        StringBuilder builder=new StringBuilder();
        for(int i=w;i<len;i++){
            builder.append(chars[i]);
        }
        for(int j=0;j<w;j++){
            builder.append(chars[j]);
        }
        String s=builder.toString();
        return s;
    }

Published 66 original articles · won praise 38 · views 4900

Guess you like

Origin blog.csdn.net/weixin_44015043/article/details/105391471