如何取字符串的前半部分,将其反转并与下半部分结合.否则,交换字符串的第一个字母和最后一个字母



如果长度可被二整除,则取字符串的前半部分并将其反转,然后与后半部分组合。否则,将字符串的第一个字母替换为最后一个字母。

String[] items = {"milk", "donut", "cookies", "cheese"};
System.out.println("Original word:n1.milkn2.donutn3.cookiesn4.cheese")
if (items[0].length() % 2 == 0) //so far I only managed to figure out the divisible.
{
//Take first half of String and reverse it and combine with second half
}
else
{
//Swap first letter to the last letter of the string
}
/* Output
Original word:
1.milk
2.donut
3.cookies
4.cheese
Divisible by two: imlk ehcese
Not Divisible by two: tonud sookiec*/ 

希望这段代码能对您有所帮助。

public class JavaMain {
public static void main(String[] args) {
String[] items = {"milk", "donut", "cookies", "cheese"};
Arrays.stream(items).forEach(System.out::println);
List<String> divByTwo    = new ArrayList<>();
List<String> nonDivByTwo = new ArrayList<>();
for(String item : items){
if (item.length() % 2 == 0) {
divByTwo.add(reverseFirstAndCombineWithSecHalf(item));
//so far I only managed to figure out the divisible.
//Take first half of String and reverse it and combine with second half
} else {
//Swap first letter to the last letter of the string
nonDivByTwo.add(String.valueOf(swapFunction(item, 0, item.length()-1)));
}
}
System.out.println("Divisible by two: " + divByTwo.stream().collect(Collectors.joining(" ")));
System.out.println("Not Divisible by two: " + nonDivByTwo.stream().collect(Collectors.joining(" ")));
}
static char[] swapFunction(String item, int from, int to){
char ch[] = item.toCharArray();
char temp = ch[from];
ch[from] = ch[to];
ch[to] = temp;
return ch;
}
static String reverseFirstAndCombineWithSecHalf(String item){
String firstHalf  = StringUtils.reverse(StringUtils.substring(item, 0, item.length() / 2));
String secondHalf = StringUtils.substring(item, item.length() / 2, item.length());
return firstHalf.concat(secondHalf);
}
}

输出为

milk
donut
cookies
cheese
Divisible by two: imlk ehcese
Not Divisible by two: tonud sookiec

使用String和StringBuilder类方法,您可以按如下方式执行:-

import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String[] items = { "milk", "donut", "cookies", "cheese" };
System.out.println(Arrays.toString(items));
for (int i = 0; i < items.length; i++) {
String item = items[i];
if (item.length() % 2 == 0) {
// Take first half of String and reverse it and combine with second half
StringBuilder firstHalf = new StringBuilder(item.substring(0, item.length() / 2));
firstHalf = firstHalf.reverse();
StringBuilder secondHalf = new StringBuilder(item.substring(item.length() / 2));
items[i] = firstHalf.append(secondHalf).toString();
} else {
// Swap first letter to the last letter of the string
items[i] = Character.toString(item.charAt(item.length() - 1)) 
+ item.substring(1, item.length()-1)
+ Character.toString(item.charAt(0));
}
}
System.out.println(Arrays.toString(items));
}
}

输出:-

[milk, donut, cookies, cheese]
[imlk, tonud, sookiec, ehcese]

最新更新