Here you can find the source of splitString(String string, int limit)
Parameter | Description |
---|---|
string | the string to split. |
limit | the char limit. |
public static List<String> splitString(String string, int limit)
//package com.java2s; /*//w ww . j a v a 2 s .c o m * JGrass - Free Open Source Java GIS http://www.jgrass.org * (C) HydroloGIS - www.hydrologis.com * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Library General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more * details. * * You should have received a copy of the GNU Library General Public License * along with this library; if not, write to the Free Foundation, Inc., 59 * Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.util.ArrayList; import java.util.List; public class Main { /** * Splits a string by char limit, not breaking works. * * @param string the string to split. * @param limit the char limit. * @return the list of split words. */ public static List<String> splitString(String string, int limit) { List<String> list = new ArrayList<String>(); char[] chars = string.toCharArray(); boolean endOfString = false; int start = 0; int end = start; while (start < chars.length - 1) { int charCount = 0; int lastSpace = 0; while (charCount < limit) { if (chars[charCount + start] == ' ') { lastSpace = charCount; } charCount++; if (charCount + start == string.length()) { endOfString = true; break; } } end = endOfString ? string.length() : (lastSpace > 0) ? lastSpace + start : charCount + start; list.add(string.substring(start, end)); start = end + 1; } return list; } }