Write a Java program that will ask the user to enter a string then copy the given string to a char array(array of characters; please see sample code below). The program will then swap the first and last word in char array and store the result in another char array.
The program should also meet the following requirements:
· It will display the original string and the new string(after swapping).
· It will display the first and last word.
· Use of StringBuffer, StringBuilder, and String class after the string was copied to an array of characters is not allowed.
· Use of any String, StringBuilder, StringBuffer, and Array method is not allowed.
· It should execute for as long as the user wants to continue.
· Create and use this method in your program:
displayArray()
{
//display array
}
import java.util.Scanner;
public class Main {
public static void displayArray(char[] array, int start, int end) {
for (int i = start; i <= end; i++) {
System.out.print(array[i]);
}
System.out.println();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String data;
while (true) {
System.out.println("Enter a string(leave empty to exit)");
data = in.nextLine();
if (data.length() == 0) {
break;
}
char[] source = data.toCharArray();
char[] swapped = new char[source.length];
int firstStart = 0;
int firstEnd = 0;
boolean firstFound = false;
int lastStart = 0;
int lastEnd = 0;
boolean lastFound = false;
for (int i = 0; i < source.length; i++) {
if (source[i] >= 'a' && source[i] <= 'z' || source[i] >= 'A' && source[i] <= 'Z') {
if (!firstFound) {
firstStart = i;
firstEnd = i;
firstFound = true;
} else {
firstEnd = i;
}
} else if (firstFound) {
break;
}
}
for (int i = source.length - 1; i >= 0; i--) {
if (source[i] >= 'a' && source[i] <= 'z' || source[i] >= 'A' && source[i] <= 'Z') {
if (!lastFound) {
lastEnd = i;
lastStart = i;
lastFound = true;
} else {
lastStart = i;
}
} else if (lastFound) {
break;
}
}
if (firstStart != lastStart) {
int j = 0;
for (int i = 0; i < firstStart; i++, j++) {
swapped[j] = source[i];
}
for (int i = lastStart; i <= lastEnd; i++, j++) {
swapped[j] = source[i];
}
for (int i = firstEnd + 1; i < lastStart; i++, j++) {
swapped[j] = source[i];
}
for (int i = firstStart; i <= firstEnd; i++, j++) {
swapped[j] = source[i];
}
for (int i = lastEnd + 1; i < source.length; i++, j++) {
swapped[j] = source[i];
}
} else {
for (int i = 0; i < source.length; i++) {
swapped[i] = source[i];
}
}
System.out.println("Source:");
displayArray(source, 0, source.length - 1);
if (firstFound) {
System.out.println("First word:");
displayArray(source, firstStart, firstEnd);
System.out.println("Last word:");
displayArray(source, lastStart, lastEnd);
}
System.out.println("After swap:");
displayArray(swapped, 0, swapped.length - 1);
}
}
}
Comments
Leave a comment