java 将字符串中的字符左移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33685946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:59:56  来源:igfitidea点击:

Shifting characters in a string to the left

java

提问by maniczebra

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:

我是 Stack Overflow 的新手,我有一个关于编程课程的实验问题,但我一直在逃避。该问题要求我们将字符串 s 的元素向左移动 k 次。例如,如果输入是“Hello World”和 3,它将输出“lo WorldHel”)。对于非常大的 k 值,它还必须相对有效地工作。这是我到目前为止:

 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!

谢谢!

回答by Simon Kraemer

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

您想要的是在位置拆分字符串k并将两个部分再次合并在一起,但顺序相反。主要问题是k可能大于或等于您的字符串的大小。所以你需要k再次带入一个有效的范围。

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

回答by R.Katnaan

Try this one my boy:

试试这个,我的孩子:

String cyclicLeftShift(String s, int k) {

    String result = s.substring(k);

    for (int i = 0; i < k; i++) {

        result += s.charAt(i);

    }

    return result;

}

回答by Chin Leung

You can try this:

你可以试试这个:

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

    for(int i=0; i<k; i++){
        result = result.substring(1) + result.charAt(0);
    }

    return result;
}

Here's an example via TutorialsPoint. Just click on compilethen executeto see the result.

这是通过TutorialsPoint的示例。只需单击编译然后执行即可查看结果。

回答by Jalai

Maybe I'm missing something, but can you not just mod k by the length of s to get n (number of characters to shift), then take the substring of [0,n) and append it to the substring [n, s.length() -1]?

也许我遗漏了一些东西,但是你能不能不只是通过 s 的长度对 k 进行模数来获得 n(要移动的字符数),然后取 [0,n) 的子字符串并将其附加到子字符串 [n, s .length() -1]?

e.g.:

例如:

String cyclicLeftShift(String s, int k){
  String result="";
  int n = k % s.length();
  result = s.substring(n) + s.substring(0,n);

  return result;
}

回答by Deepak Srinivas

Not sure if this solution is of help ! But it worked for me :) Well you could try it out!

不确定这个解决方案是否有帮助!但它对我有用:) 好吧,你可以试试看!

 class Main {
  public static void main(String[] args) {
    System.out.println("Moving left by n characters");
    String str1 = moveCHaracters("Hellow World", 4);
    System.out.println(str1);
  }

  public static String moveCHaracters(String s, int k) {
    String result = s.substring(s.length() - (k));
    int length = s.length() - k;
    if (k > 0) {
      for (int i = 0; i < length; i++) {
        result = result + s.charAt(i);
      }
    }
    return result;
  }
}

回答by Jay

A quick solution, just need to take care that the valto be shifted must not be OutOfBounds.

一个快速的解决方案,只需要注意要移动的val不能是 OutOfBounds。

String shiftLeft(String inp, int val)
{
     String shifted_str="";
     shifted_str=inp.substring(val);
     shifted_str+=inp.substring(0,val);
     return shifted_str;        
}

回答by Matt Timmermans

The arguments to String.substring() are (beginIndex, endIndex), NOT (beginIndex, count). You need to pass s.length() instead of s.length()-1... Or you could do it one of the much faster ways that others are posting

String.substring() 的参数是 (beginIndex, endIndex), NOT (beginIndex, count)。您需要通过 s.length() 而不是 s.length()-1 ... 或者您可以通过其他人发布的更快的方式之一进行