我正在尝试更新我之前写过的代码"旋转字符串。"目前我的程序接受来自键盘输入和整数n的字符串。恩。 " abcdefg",3。然后在返回旋转的字符串之前将字符串旋转n个字符,即" efgabcd"。现在是棘手的部分。我试图更新这个以基本相同的东西,但用句子。所以输入就像"这是一个例子"和整数3.然后输出将是"这是一个例子。"我假设将句子分成数组将是我最好的选择;但是我对字符串的不熟悉并不能让我知道如何去做。
O(1)
答案 0 :(得分:2)
以下是一个示例解决方案:
str
int num = 3;
String str = "This is a test";
List<String> parts = Arrays.asList(str.split(" "));
Collections.rotate(parts, 3);
String.join(" ", parts);
现在包含&#34;是测试此&#34;。
编辑:固定向右旋转。
我实际上更喜欢@fergDEV的解决方案,但如果您使用的是Java 8,可以稍微清理一下:
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
答案 1 :(得分:1)
Collections utils是你的朋友:P。
public class Main {
public static String rotateSetence(final String input, final int rotation) {
final List<String> results = Arrays.asList(input.split(" "));
Collections.rotate(results, rotation);
final StringBuilder outputBuilder = new StringBuilder();
for (int i = 0; i < results.size(); i++) {
outputBuilder.append(results.get(i));
if (i != results.size() - 1)
outputBuilder.append(" ");
}
return outputBuilder.toString();
}
public static void main(String[] args) {
final String inputString = "This is an example";
final int sentenceRotation = 3;
final String expectedResult = "is an example This";
final String result = rotateSetence(inputString, sentenceRotation);
System.out.println("result " + result);
if (result.equals(expectedResult)) {
System.out.println("Passed");
} else {
System.out.println("Failed");
}
}
}
修改
构建器代码可以替换为string.join ...感谢@shmosel。
final StringBuilder outputBuilder = new StringBuilder();
for (int i = 0; i < results.size(); i++) {
outputBuilder.append(results.get(i));
if (i != results.size() - 1)
outputBuilder.append(" ");
}
return outputBuilder.toString();
可以替换为
return String.join(" ", results);
答案 2 :(得分:0)
你也可以使用两个for循环,这样在第一个for循环中你可以从num(由用户提供)位置循环到字符串的结尾。在第二个循环中,您从字符串的开头循环到num的位置。
要使上述逻辑起作用,您显然需要将使用空格的字符串拆分为字符串数组。见下文:
public static String rotate(String s, int num)
{
//split the sentence by space
String[] chunks = s.split(" ");
//use StringBuilder to build rotated string
StringBuilder builder = new StringBuilder();
//loop from position specified by user to end of array
for(int i = num; i < chunks.length; i++) {
builder.append(chunks[i] + " ");
}
//loop from start of array to position specified by user
for(int i = 0; i < num; i++) {
builder.append(chunks[i] + " ");
}
return builder.toString();
}
输入和输出如下所示:
Enter a string:My name is Raf and I am super super fun guy trust me
Enter the number of characters that you want to rotated to right:2
The rotated string is : is Raf and I am super super fun guy trust me My name