Java tutorial
//package com.java2s; /** * Copyright (c) 2013, 2014 Denis Nikiforov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Denis Nikiforov - initial API and implementation */ public class Main { public static int getCharPositionInLine(String text, int offset) { return getLineAndCharPosition(text, offset)[1]; } public static Integer[] getLineAndCharPosition(String text, int offset) { int index = 0; int line = 0; int positionInLine = 0; while (true) { line++; positionInLine = offset - index + 1; int nextN = text.indexOf("\n", index); int nextR = text.indexOf("\r", index); int nextNorR = Integer.MAX_VALUE; if (nextN >= 0) { nextNorR = nextN; } else if (nextR >= 0 && nextR < nextNorR) { nextNorR = nextR; } else { // found no EOL character break; } index = nextNorR + 1; if (index == nextN) { index++; } if (index == nextR) { index++; } if (index > offset) { break; } } return new Integer[] { line, positionInLine }; } }