Here you can find the source of getOffspringStrings(int startIndex, String treeStr)
Parameter | Description |
---|---|
startIndex | a parameter |
treeStr | a parameter |
protected static List<String> getOffspringStrings(int startIndex, String treeStr)
//package com.java2s; /******************************************************************** * * Copyright 2011 Brendan O'Fallon//w ww . ja v a 2 s . c o m * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***********************************************************************/ import java.util.ArrayList; import java.util.List; public class Main { /** * Return a list of strings representing the children descending from the subtree that * begins at the position startIndex * @param startIndex * @param treeStr * @return String representing the subtrees that start at the given position */ protected static List<String> getOffspringStrings(int startIndex, String treeStr) { ArrayList<String> children = new ArrayList<String>(); treeStr = treeStr.trim(); int lastParen = matchingParenIndex(startIndex, treeStr); //Scan along subtree string, create new strings separated by commas *at 'highest level'* //not all commas, of course int i = startIndex + 1; StringBuffer cstr = new StringBuffer(); int count = 0; for (i = startIndex + 1; i < lastParen; i++) { if (treeStr.charAt(i) == '(') count++; if (treeStr.charAt(i) == ')') count--; if (treeStr.charAt(i) == ',' && count == 0) { children.add(cstr.toString()); cstr = new StringBuffer(); } else cstr.append(treeStr.charAt(i)); } children.add(cstr.toString()); return children; } /** * Find the index of the parenthesis that matches the given paren * @param firstPos Index of opening paren * @param str String to search in * @return Index of closing paren that matches the given start paren */ private static int matchingParenIndex(int firstPos, String str) { int i = firstPos; if (str.charAt(i) != '(') { System.err.println("Got a non-paren for first index in find matching paren"); System.err.println(" Char is : |" + str.charAt(i) + "|"); return -1; } int count = 0; for (i = firstPos; i < str.length(); i++) { if (str.charAt(i) == '(') count++; if (str.charAt(i) == ')') count--; if (count == 0) return i; } System.err.println("Couldn't find matching paren for this string : |" + str + "|"); System.err.println(" First paren index : " + firstPos); return -1; } }