Game-of-Life-WSU-CEG4180  v0.1
RefactoringtheGameofLife
LineEnumerator.java
Go to the documentation of this file.
1 /* This page is part of the Game of Life source code */
2 
3 /*
4  * Enumerates over a string containing a text file, returning lines.
5  */
6 package org.bitstorm.util;
7 
8 import java.util.Enumeration;
9 
10 /**
11  * Enumerates over a string containing a text file, returning lines.
12  * Line endings in the text can be "\r\n", "\r" or "\n".
13  * @author Edwin Martin
14  */
15 // But nothing beats Python ;-)
16 // for line in file("file.txt"):
17 // # Process line
18 public class LineEnumerator implements Enumeration {
19  private final String s;
20  private final String separator;
21  public final String CR = "\r";
22  public final String LF = "\n";
23  public final String CRLF = "\r\n";
24  int offset;
25  int eolOffset;
26 
27  /**
28  * Constructs a TextEnumerator.
29  * @param s String with text
30  */
31  public LineEnumerator( String s ) {
32  this.s = s;
33  // find out the seperator
34  if ( s.indexOf( CR ) != -1 ) {
35  if ( s.indexOf( CRLF ) != -1 )
36  separator = CRLF;
37  else
38  separator = CR;
39  } else {
40  separator = LF;
41  }
42  eolOffset = -separator.length();
43  }
44  /**
45  * @see java.util.Enumeration#hasMoreElements()
46  */
47  public boolean hasMoreElements() {
48  return eolOffset != s.length();
49  }
50  /**
51  * When the "last line" ends with a return, the next empty line will also be returned, as it should.
52  * Returned lines do not end with return chars (LF, CR or CRLF).
53  * @see java.util.Enumeration#nextElement()
54  */
55  public Object nextElement() {
56  // skip to next line
57  offset = eolOffset+separator.length();
58  // find the next seperator
59  eolOffset = s.indexOf( separator, offset );
60  // not found, set to last char (the last line doesn't need have a \n or \r)
61  if ( eolOffset == -1 )
62  eolOffset = s.length();
63  return s.substring( offset, eolOffset );
64  }
65 }