How to take first half of String and reverse it and combine it with second half. Otherwise Swap the first letter and last letter of String [closed]
Hope this code helps you.
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);
}
}
Output would be
milk
donut
cookies
cheese
Divisible by two: imlk ehcese
Not Divisible by two: tonud sookiec