Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.ArrayList;
- public class ColumnedString {
- private final String raw;
- private final String screenReader;
- public ColumnedString(String raw) {
- this.raw = raw;
- this.screenReader = this.divideColumns(raw);
- }
- private String divideColumns(String source) {
- StringBuilder result = new StringBuilder();
- StringBuilder curSB;
- ArrayList<StringBuilder> columns = new ArrayList<StringBuilder>();
- ArrayList<Integer> curColumns = new ArrayList<Integer>();
- String[] lineColumns;
- BufferedReader br = new BufferedReader(new StringReader(source));
- String line;
- try {
- while ((line = br.readLine()) != null) {
- // split lines into columns, where columns are separated by one or more |
- // also, strip any excess white space
- lineColumns = line.split(" *\\|+ *");
- while (lineColumns.length < curColumns.size()) {
- // truncate columns no longer in use
- curColumns.remove(curColumns.size()-1);
- }
- while (lineColumns.length > curColumns.size()) {
- // add new columns
- curColumns.add(columns.size());
- columns.add(new StringBuilder());
- }
- for (int i = 0; i < lineColumns.length; i++) {
- curSB = columns.get(curColumns.get(i));
- if (curSB.length() > 0 && curSB.charAt(curSB.length()-1) != ' ') {
- // separate lines of the same column with a space if they aren't already
- curSB.append(' ');
- }
- curSB.append(lineColumns[i]);
- }
- }
- } catch (IOException e) {
- // why would a StringReader even throw an exception on readLine()? *_*
- }
- String separator = "";
- for (int i = 0; i < columns.size(); i++) {
- if (columns.get(i).length() == 0) {
- // don't add empty columns - they're presumably just visual artifacts anyway
- continue;
- }
- result.append(separator).append(columns.get(i));
- separator = "\n\n";
- }
- return result.toString();
- }
- public String getRaw() {
- return this.raw;
- }
- public String getScreenReader() {
- return this.screenReader;
- }
- // driver function
- public static void main(String args[]) {
- String test = "| Column 1 text | column 2 text | column 3\n" +
- "| could go here | could go here\n" +
- "| end of column 1 | | column 4";
- ColumnedString cs = new ColumnedString(test);
- System.out.println("-ORIGINAL-");
- System.out.println(cs.getRaw());
- System.out.println("-SCREEN READER-");
- System.out.println(cs.getScreenReader());
- System.out.println("-END-");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement