/** * Assignment 2, COMP268 Class: ReversedSentence.java * * @description Provides a class to manipulating strings. * @author: mo khan Student ID: 3431709 * @date Jun 2, 2019 * @version 1.0 */ package Q1; import java.util.Scanner; public class ReversedSentence { /** * Replaces the every character that is in an index that is evenly divisible by 5 with the * character 'z', excluding 0. * * @param s The input string to substitue * @return The new string with the substitution. */ public static String change5thPosition(String s) { char[] result = new char[s.length()]; for (int i = 0; i < s.length(); i++) result[i] = (i > 0 && i % 5 == 0) ? 'z' : s.charAt(i); return new String(result); } /** * Combines the 2D array of character into a printable string. * * @param arr the two dimensional array of characters. * @return a String of the combined character arrays separated by a line separator. */ public static String printChar2DArray(char[][] arr) { String[] strings = new String[arr.length]; for (int i = 0; i < arr.length; i++) strings[i] = new String(arr[i]); return String.join(System.lineSeparator(), strings); } /** * Reverses a string. * * @param s the input String to reverse * @return the reversed String. */ public static String reverseByCharacter(String s) { char[] result = new char[s.length()]; int length = s.length(); for (int i = 0; i < length; i++) result[length - i - 1] = s.charAt(i); return new String(result); } /** * Reverses the words in a string * * @param s the input string to reverse * @return a string with the words in reverse order */ public static String reverseByWord(String s) { String[] words = s.split(" "); String[] result = new String[words.length]; for (int i = 0; i < words.length; i++) { String word = words[i]; result[words.length - i - 1] = word; } return String.join(" ", result); } /** * Truncates a tring to a maximum of 80 characters. * * @param s the input string to truncate * @return the truncated string */ public static String truncateSentence(String s) { return s.substring(0, Math.min(s.length(), 80)); } /** * The entry point for the console application. * * @param args the commandline arguments passed to the program */ public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] sentences = new String[3]; for (int i = 0; i < 3; i++) { System.out.println(String.format("Enter sentence %d: (max 80 characters)", i + 1)); sentences[i] = ReversedSentence.truncateSentence(in.nextLine()); } char[][] matrix = new char[3][80]; matrix[0] = ReversedSentence.reverseByCharacter(sentences[0]).toCharArray(); matrix[1] = ReversedSentence.reverseByWord(sentences[1]).toCharArray(); matrix[2] = ReversedSentence.change5thPosition(sentences[2]).toCharArray(); System.out.println(); System.out.println("Result: "); System.out.println(); System.out.print(ReversedSentence.printChar2DArray(matrix)); System.out.println(); System.out.println(); System.out.println("Bye"); } }