Created
April 14, 2016 14:23
-
-
Save wowselim/9a507c97e8b5a2c84bac34317c342043 to your computer and use it in GitHub Desktop.
Answer to followup question on https://stackoverflow.com/questions/36618399/how-do-i-start-a-new-line-after-a-period-question-mark-and-exclamation-point/36618517
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
public class TextSplitter { | |
public static void main(String[] args) { | |
// These are just two lines that you have read from a file: | |
String firstLine = "hello? bartender. can I have a drink!whiskey please."; | |
String secondLine = "another. line."; | |
// This is a list containing all the two lines you have read: | |
List<String> lines = Arrays.asList(firstLine, secondLine); | |
// This is the list that will contain all the new lines: | |
List<String> result = new ArrayList<>(); | |
// Looping through the two lines | |
for (String line : lines) { | |
// Adding newlines after punctuation marks followed by a space: | |
line = line.replace("? ", "?\n").replace("! ", "!\n").replace(". ", ".\n"); | |
// Splitting the line by the newly created newline characters: | |
String[] resultingLinesAfterReplacement = line.split("\n"); | |
// Looping through the resulting lines: | |
for (String resultingLine : resultingLinesAfterReplacement) | |
// Adding them to the result list: | |
result.add(resultingLine.substring(0, 1).toUpperCase() + resultingLine.substring(1)); | |
} | |
// Print the result: | |
System.out.println(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment