Java String Line Count countLineEnds(CharSequence string, int startPos)

Here you can find the source of countLineEnds(CharSequence string, int startPos)

Description

Returns the number of line ends considering returns and new lines in string after startPos.

License

Apache License

Parameter

Parameter Description
string the string to analyze
startPos the start position within string

Return

the number of line ends

Declaration

public static int countLineEnds(CharSequence string, int startPos) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from   www.  j a  va 2s  .co m
     * Returns the number of line ends considering returns and new lines in <code>string</code>
     * after <code>startPos</code>.
     * 
     * @param string the string to analyze
     * @param startPos the start position within string
     * @return the number of line ends
     */
    public static int countLineEnds(CharSequence string, int startPos) {
        int count = 0;
        int i = startPos;
        while (i < string.length()) {
            char c = string.charAt(i);
            if ('\r' == c) {
                count++;
                i = advanceIfNextIsNewLine(string, i);
            } else if ('\n' == c) {
                count++;
            }
            i++;
        }
        return count;
    }

    /**
     * Advance the given position if it is a new line.
     * 
     * @param text the text to analyze
     * @param pos the position
     * @return the (not) advanced position
     */
    private static int advanceIfNextIsNewLine(CharSequence text, int pos) {
        int result = pos;
        if (nextIs(text, pos, '\n')) {
            result++;
        }
        return result;
    }

    /**
     * Returns whether the next character in <code>text</code> after <code>pos</code> is <code>ch</code>.
     * 
     * @param text the text to analyze
     * @param pos the position
     * @param ch the character to look for
     * @return <code>true</code> if the next character is <code>ch</code>, <code>false</code> else
     */
    private static boolean nextIs(CharSequence text, int pos, char ch) {
        return pos + 1 < text.length() && ch == text.charAt(pos + 1);
    }
}

Related

  1. countLine(CharSequence str)
  2. countLine(String content)
  3. countLine(String contents, int index)
  4. countLineBreaks(final String replacementString)
  5. countLineBreaks(String text)
  6. countLines(final String content, final String lineBreak)
  7. countLines(String aMessage)
  8. countLines(String buffer)
  9. countLines(String data)