Java 围绕中间字符交换字符串
我有一个关于字符串反转的问题,但它不是完全反转 如果输入为Java 围绕中间字符交换字符串,java,string,Java,String,我有一个关于字符串反转的问题,但它不是完全反转 如果输入为XYAF,则输出应为AFXYXY是前半部分,移动到另一侧 如果输入为XYZAF,则输出应为AFZXYXY是前半部分并向右移动AF是下半部分并向左移动 z < /代码>停留在中间。 我们怎么做?我已经制定了一个可行的计划,但我认为它不是很有效。还有别的办法吗 String str = "XYAF"; //Output Should be AFXY String str1 = "XYZAF"; // Output should
XYAF
,则输出应为AFXY
XY
是前半部分,移动到另一侧
如果输入为XYZAF
,则输出应为AFZXY
<代码>XY是前半部分并向右移动AF
是下半部分并向左移动<代码> z < /代码>停留在中间。
我们怎么做?我已经制定了一个可行的计划,但我认为它不是很有效。还有别的办法吗
String str = "XYAF"; //Output Should be AFXY
String str1 = "XYZAF"; // Output should be AFZXY
int length = str1.length();
int mid = length / 2;
String output = "" ;
if (length % 2 == 0) {
// Even length then divide the string in equal parts
String x1 = str1.substring(0, mid);
String x2 = str1.substring(mid, length);
x3= x2+x1;
} else {
// Odd number and we want to
// xyz and output should be zyx
String x1 = str1.substring(0, mid);
String x2 = str1.substring(mid + 1, length);
x3 = x2 + str1.charAt(mid) + x1;
}
提前感谢,您的代码看起来完全正常且足够高效 也许你只是想以不同的方式组织它:
String[] tests = {"XYAF", "XYZAF"};
for (String test : tests) {
int length = test.length();
int mid = length / 2;
String firstHalf = test.substring(0, mid);
String midPoint = (length % 2 == 0) ? "" : test.substring(mid, mid+1);
String secondHalf = test.substring(mid + midPoint.length(), length);
String output = firstHalf + midPoint + secondHalf;
}
还可以使用第二个中间点将奇数/偶数除以2
private String midSwap(String s) {
// Find the middle rounded down to an integer.
int mid1 = s.length() / 2;
// If length is odd then this will be mid1 + 1
int mid2 = (s.length() + 1) / 2;
return s.substring(mid2) + s.substring(mid1, mid2) + s.substring(0, mid1);
}
private void test(String s) {
System.out.println(s + " -> " + midSwap(s));
}
public void test(String[] args) {
test("XYAF");
test("XYZAF");
}
@Jeena你只是向我们展示了你需求的一部分(一个例子),没有完整的说明你需要什么/想要什么和不需要什么好吧,你说得对,我认为这不是很有效:是的。为什么不呢?请更改标题。这不是字符串反转,这是子字符串交换midpoint@Jeena这不是一个规范。这是模棱两可的。在不阅读代码的情况下,我可以从该示例中推断出,如果输入字符串是ertyuiaf,那么输出应该是afertyui(例如)。