Skip to content

Instantly share code, notes, and snippets.

@trivalent
Created December 16, 2023 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trivalent/64633a4fea0ad54925758bbb1b14b44f to your computer and use it in GitHub Desktop.
Save trivalent/64633a4fea0ad54925758bbb1b14b44f to your computer and use it in GitHub Desktop.
import org.junit.Test;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
class Scratch {
static class HSBC {
/**
* Reverse the contents of the file and write the output into output.txt
* @param inputFile: The file name/path to be reversed
* return: void
*/
public void reverseFile(String inputFile) throws IOException {
try(Stream<String> stream = Files.lines(Paths.get(inputFile))) {
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
stream.forEach(line -> {
try {
writer.write(reverseString(line));
} catch (IOException e) {
e.printStackTrace();
}
});
writer.close();
}
}
public String reverseString(String inputString) {
boolean isAscii = inputString.chars().allMatch(c -> c < 128);
if (!isAscii)
throw new IllegalArgumentException("Can't reverse a non-ASCII string");
StringBuilder output = new StringBuilder(inputString.length());
StringBuilder reversal = new StringBuilder();
String[] words = inputString.split("\\s+");
for (String word : words) {
reversal.append(word);
reversal.reverse();
output.append(reversal);
output.append(" ");
reversal.setLength(0);
}
return output.toString();
}
@Test
public void testReverseString() {
String words = "This is a sample test";
String output = reverseString(words);
assert !output.equals("sihT si a elpmas tset");
}
}
public static void main(String[] args) {
HSBC hsbc = new HSBC();
hsbc.testReverseString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment