Here you can find the source of splitByNonNestedChars(String s, char... c)
Parameter | Description |
---|---|
s | The string to split. |
c | The chars by which to split s. |
public static String[] splitByNonNestedChars(String s, char... c)
//package com.java2s; /*//from ww w .ja v a2s . co m Solve4x - An algebra solver that shows its work Copyright (C) 2015 Nathaniel Paulus This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.ArrayList; public class Main { /** * Splits string s by any chars c for every occurrence of chars c that are not nested in parentheses. * The characters at which s is split will be included at the beginning of the respective elements. * Occurrences of chars c at the beginning of s will be ignored. * Examples: * splitByNonNestedChars("xy+6-4", '+', '-') returns ["xy", "+6", "-4"] * splitByNonNestedChars("(4x)/(6y(2+x))", '/') returns ["(4x)", "/(6y(2+x))"] * @param s The string to split. * @param c The chars by which to split s. * @return A string array of s split by occurrences of chars c not nested in parentheses. */ public static String[] splitByNonNestedChars(String s, char... c) { //get setup int parDepth = 0; String chars = new String(c); ArrayList<String> parts = new ArrayList<String>(); //search for matches for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') parDepth++; else if (s.charAt(i) == ')') parDepth--; //if it's a char we split at, and it's not the first one else if (parDepth == 0 && i != 0 && chars.indexOf(s.charAt(i)) != -1) { parts.add(s.substring(0, i)); s = s.substring(i); i = 0; } } parts.add(s); // add the rest of the string return parts.toArray(new String[parts.size()]); } }