Example usage for java.lang StringBuilder subSequence

List of usage examples for java.lang StringBuilder subSequence

Introduction

In this page you can find the example usage for java.lang StringBuilder subSequence.

Prototype

CharSequence subSequence(int start, int end);

Source Link

Document

Returns a CharSequence that is a subsequence of this sequence.

Usage

From source file:Main.java

public static void main(String[] arg) {

    StringBuilder buffer = new StringBuilder("from java2s.com");

    System.out.println(buffer.subSequence(1, 2));
}

From source file:Main.java

private static CharSequence cut(StringBuilder sb, int start, int end) {
    CharSequence cs = sb.subSequence(start, end);
    sb.delete(start, end);/*from  w w w  .j a  v a  2s .co m*/
    return cs;
}

From source file:Main.java

public static String joinArray(int[] arr, String seperator) {
    StringBuilder sb = new StringBuilder();
    for (Integer i : arr) {
        sb.append(i).append(seperator);//  w  ww . j a va  2s  .c o m
    }

    if (sb.length() > 0) {
        return sb.subSequence(0, sb.length() - seperator.length()).toString();
    }
    return sb.toString();
}

From source file:com.joyent.manta.util.MantaUtils.java

/**
 * Checks to see if a {@link StringBuilder} ends with a given character.
 *
 * @param builder StringBuilder to check
 * @param match character to match//from  w  w  w.  ja  v a2 s .c om
 * @return true if last character in StringBuilder matches
 */
public static boolean endsWith(final StringBuilder builder, final char match) {
    Validate.notNull(builder, "StringBuilder object must not be null");

    if (builder.length() == 0) {
        return false;
    }

    final char last = builder.subSequence(builder.length() - 1, builder.length()).charAt(0);
    return last == match;
}

From source file:edu.chalmers.dat076.moviefinder.service.TitleParser.java

/**
 * Removes everything starting from index n until the char c. If interval
 * contains a positive 4 digit number (and nothing else) it is returned,
 * otherwise -1 is returned./*from ww  w  .  j a v  a 2 s  .  c  o  m*/
 *
 * @param mySb
 * @param n
 * @param c
 * @return if interval contains a number it is returned
 */
public int removeUntil(StringBuilder mySb, int n, char c) {
    int re = -1;

    for (int i = n; i <= mySb.length(); i++) {
        if (mySb.charAt(i) == c) {
            if (i - n == 5) {
                re = checkForYear(mySb.subSequence(n + 1, i));
            }
            mySb.delete(n, i + 1);
            break;
        }
    }
    return re;
}

From source file:com.prowidesoftware.swift.model.SwiftBlock2Output.java

/**
 * Sets the MIR (Message Input Reference) attributes by parsing the string argument containing the complete MIR value.<br /> 
 * For example YYMMDDBANKBEBBAXXX2222123456<br>
 * /*from   w  ww  .  j a v  a  2s  . c  o m*/
 * @param mir complete MIR string
 * @param lenient if true the value will be parsed with a best effort heuristic, if false it will throw a IllegalArgumentException if the value has an invalid total size
 */
public void setMIR(final String mir, boolean lenient) {
    if (!lenient) {
        Validate.notNull(mir);
        Validate.isTrue(mir.length() == 28,
                "expected a 28 characters string for MIR value and found a " + mir.length() + " string:" + mir);
    }
    if (mir != null) {
        final StringBuilder sb = new StringBuilder(mir);

        int offset = 0;
        int len;

        len = 6;
        this.setMIRDate(String.valueOf(sb.subSequence(offset, offset + len)));
        offset += len;

        len = 12;
        this.setMIRLogicalTerminal(String.valueOf(sb.subSequence(offset, offset + len)));
        offset += len;

        len = 4;
        this.setMIRSessionNumber(String.valueOf(sb.subSequence(offset, offset + len)));
        offset += len;

        if (lenient) {
            //get all remaining text
            this.setMIRSequenceNumber(String.valueOf(sb.subSequence(offset, mir.length())));
        } else {
            len = 6;
            this.setMIRSequenceNumber(String.valueOf(sb.subSequence(offset, offset + len)));
            offset += len;
        }
    }
}

From source file:com.ibm.bi.dml.yarn.DMLYarnClient.java

/**
 * This is our fallback strategy for obtaining our SystemML.jar that we need
 * to submit as resource for the yarn application. We repackage the unzipped
 * jar to a temporary jar and later copy it to hdfs.
 * /* ww w . j a  v a2  s  .c  o  m*/
 * @param dir
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
private String createJar(String dir) throws IOException, InterruptedException {
    //construct jar command
    String jarname = dir + "/" + DML_JAR_NAME;
    File fdir = new File(dir);
    File[] tmp = fdir.listFiles();
    StringBuilder flist = new StringBuilder();
    for (File ftmp : tmp) {
        flist.append(ftmp.getName());
        flist.append(" ");
    }

    //get jdk home (property 'java.home' gives jre-home of parent jdk or standalone)
    String javahome = System.getProperty("java.home");
    File fjdkhome = new File(new File(javahome).getParent() + File.separator + "bin");
    String jarPrefix = "";
    if (fjdkhome.exists()) { //exists if jdk
        jarPrefix = fjdkhome.getAbsolutePath();
        jarPrefix += File.separator;
    }
    if (jarPrefix.isEmpty())
        LOG.warn("Failed to find jdk home of running jre (java.home=" + javahome + ").");

    //execute jar command
    String command = jarPrefix + "jar cf " + jarname + " " + flist.subSequence(0, flist.length() - 1);
    LOG.debug("Packaging jar of unzipped files: " + command);
    Process child = Runtime.getRuntime().exec(command, null, fdir);
    int c = 0;
    while ((c = child.getInputStream().read()) != -1)
        System.out.print((char) c);
    while ((c = child.getErrorStream().read()) != -1)
        System.err.print((char) c);
    child.waitFor();

    return jarname;
}

From source file:hudson.plugins.emailext.plugins.content.BuildLogMultilineRegexContent.java

private String getContent(BufferedReader reader) throws IOException {
    final Pattern pattern = Pattern.compile(regex);
    final boolean asHtml = matchedSegmentHtmlStyle != null;
    escapeHtml = asHtml || escapeHtml;//from   w ww. j  av  a2s  .  c  o m

    StringBuilder line = new StringBuilder();
    StringBuilder fullLog = new StringBuilder();
    int ch;
    // Buffer log contents including line terminators, and remove console notes
    while ((ch = reader.read()) != -1) {
        if (ch == '\r' || ch == '\n') {
            if (line.length() > 0) {
                // Remove console notes (JENKINS-7402)
                fullLog.append(ConsoleNote.removeNotes(line.toString()));
                line.setLength(0);
            }
            fullLog.append((char) ch);
        } else {
            line.append((char) ch);
        }
    }
    // Buffer the final log line if it has no line terminator
    if (line.length() > 0) {
        // Remove console notes (JENKINS-7402)
        fullLog.append(ConsoleNote.removeNotes(line.toString()));
    }
    StringBuilder content = new StringBuilder();
    int numMatches = 0;
    boolean insidePre = false;
    int lastMatchEnd = 0;
    final Matcher matcher = pattern.matcher(fullLog);
    while (matcher.find()) {
        if (maxMatches != 0 && ++numMatches > maxMatches) {
            break;
        }
        if (showTruncatedLines) {
            if (matcher.start() > lastMatchEnd) {
                // Append information about truncated lines.
                int numLinesTruncated = countLineTerminators(
                        fullLog.subSequence(lastMatchEnd, matcher.start()));
                if (numLinesTruncated > 0) {
                    insidePre = stopPre(content, insidePre);
                    appendLinesTruncated(content, numLinesTruncated, asHtml);
                }
            }
        }
        if (asHtml) {
            insidePre = startPre(content, insidePre);
        }
        if (substText != null) {
            final StringBuffer substBuf = new StringBuffer();
            matcher.appendReplacement(substBuf, substText);
            // Remove prepended text between matches
            final String segment = substBuf.substring(matcher.start() - lastMatchEnd);
            appendMatchedSegment(content, segment, escapeHtml, matchedSegmentHtmlStyle);
        } else {
            appendMatchedSegment(content, matcher.group(), escapeHtml, matchedSegmentHtmlStyle);
        }
        lastMatchEnd = matcher.end();
    }
    if (showTruncatedLines) {
        if (fullLog.length() > lastMatchEnd) {
            // Append information about truncated lines.
            int numLinesTruncated = countLineTerminators(fullLog.subSequence(lastMatchEnd, fullLog.length()));
            if (numLinesTruncated > 0) {
                insidePre = stopPre(content, insidePre);
                appendLinesTruncated(content, numLinesTruncated, asHtml);
            }
        }
    }
    stopPre(content, insidePre);
    return content.toString();
}

From source file:edu.chalmers.dat076.moviefinder.service.TitleParser.java

private TemporaryMedia getInformation(StringBuilder mySb) {

    TemporaryMedia returnMedia = new TemporaryMedia();
    StringBuilder wordSb = new StringBuilder();

    int tmpYear;/*from w w  w  .  j  a  v a  2  s. c  o m*/
    int year = -1;
    int thisYear = Calendar.getInstance().get(Calendar.YEAR);

    boolean deleteYear = false;
    boolean finalWord = true;

    for (int i = 0; i < mySb.length(); i++) {
        if (mySb.charAt(i) == '.' || mySb.charAt(i) == ' ' || mySb.charAt(i) == '-' || mySb.charAt(i) == '_') {

            if (Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
                mySb.delete(i - (wordSb.length() + 1), mySb.length());
                finalWord = false;
                // final useful word found. No point in continuing.
                break;
            }
            mySb.replace(i, i + 1, " ");

            tmpYear = checkForYear(wordSb);
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = true;
            }
            wordSb.setLength(0);

        } else if (wordSb.length() == 0
                && (mySb.charAt(i) == 'S' || mySb.charAt(i) == 's' || Character.isDigit(mySb.charAt(i)))) {
            // See if new word contains series and episode information.

            StringBuilder whatsLeft = new StringBuilder(mySb.subSequence(i, mySb.length()));
            if (getEpisodePotential(whatsLeft)) {
                TemporaryMedia tmpMedia = getEpisodeInfo(whatsLeft);
                returnMedia.setIsMovie(false);
                returnMedia.setSeason(tmpMedia.getSeason());
                returnMedia.setEpisode(tmpMedia.getEpisode());
                mySb.delete(i, mySb.length());
                // series and episode information saved. No point in continuing.
                break;

            } else {
                wordSb.append(mySb.charAt(i));
            }
        } else if (mySb.charAt(i) == '[' || mySb.charAt(i) == '(') {
            // Brackets shoudl usually be removed. They could possibly contain realease year.

            if (Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
                mySb.delete(i - (wordSb.length() + 1), mySb.length());
                finalWord = false;
                // final useful word found. No point in continuing.
                break;
            }
            tmpYear = checkForYear(wordSb);
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = true;
            }
            wordSb.setLength(0);

            if (mySb.charAt(i) == '[') {
                tmpYear = removeUntil(mySb, i, ']');
            } else if (mySb.charAt(i) == '(') {
                tmpYear = removeUntil(mySb, i, ')');
            }
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = false;
            }
            i--; // Need to compensate for removing bracket.

        } else {
            // Nothing useful here. Save the char and continue.
            wordSb.append(mySb.charAt(i));
        }
    }

    if (finalWord && Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
        mySb.delete(mySb.length() - wordSb.length(), mySb.length());
    } else {
        tmpYear = checkForYear(wordSb);
        if (tmpYear > 1900 && tmpYear <= thisYear) {
            year = tmpYear;
            deleteYear = true;
        }
    }
    if (deleteYear && returnMedia.IsMovie()) {
        int i = mySb.lastIndexOf(year + "");
        mySb.delete(i, i + 4);
    }

    returnMedia.setYear(year);
    returnMedia.setName(mySb.toString().trim());

    return returnMedia;
}

From source file:com.edgenius.wiki.render.filter.MacroFilter.java

/**
 * Some macro has group concept. For example, table and cell, tabs and tab. To process these 
 * relative macro, this method parses text and insert a "group key" into these macro as a part of parameters. 
 * During macro process, it is able to MacroParameter.getParam(Macro.GROUP_KEY) to get back the group key. 
 * The group key contains this group unique number, the children macro unique number etc. For example,
 * a 2x2 table will insert following group keys(edgnius_group_key as name). 
 * <pre>//from   w ww .j  a va 2s . c  o m
    {table:edgnius_group_key=0}
   {cell:edgnius_group_key=0-0-0-2}
   123
   {cell}
   {cell:edgnius_group_key=0-0-1-2}
   abc
   {cell}
   {rowdiv:edgnius_group_key=0-1}
   {cell:edgnius_group_key=0-1-0-2}
   456
   {cell}
   {cell:edgnius_group_key=0-1-1-2}
   def
   {cell}
   {table}
 * </pre>
 * 
 * For 2 tabs deck:
 * <pre>
   {tabs:edgnius_group_key=0}
   {tab:edgnius_group_key=0-1|name=work}
   working for money
   {tab}
   {tab:edgnius_group_key=0-2|name=life}
   life for fun
   {tab}
   {tabs}
 * </pre>
 * @param text
 * @return
 */
public String initialGroup(String text) {
    CharSequence buffer = MarkupUtil.hideEscapeMarkup(text);

    LinkedList<GroupProcessor> stack = new LinkedList<GroupProcessor>();
    List<GroupProcessor> processors = new ArrayList();
    checkGroup(0, buffer, stack, processors);

    //insert group id into text
    if (processors.size() > 0) {
        //sort processor first, so that it becomes easier when insert - just insert one by one 
        //without worries of position change impact
        Map<Integer, GroupProcessor> borders = new TreeMap<Integer, GroupProcessor>(new CompareToComparator(
                CompareToComparator.TYPE_OVERWRITE_SAME_VALUE | CompareToComparator.DESCEND));
        for (GroupProcessor gp : processors) {
            Set<Integer> posList = gp.getPositions();
            for (Integer pos : posList) {
                borders.put(pos, gp);
            }
        }

        //recreate new stringBuilder as buffer(from first line of this method) is escaped
        StringBuilder sb = new StringBuilder(text);
        //on behalf of above sort result, insert is simple, just looping borderPoint one by one as new insert won't impact 
        //the others un-inserted point location.
        for (Entry<Integer, GroupProcessor> entry : borders.entrySet()) {
            GroupProcessor gp = entry.getValue();
            int start = entry.getKey();
            if (gp.suppressNewlineBetweenElements()) {
                //Here want to remove newline between table and cells. There are 2 tricks here, as example,
                //(A){table} 
                //(B1){cell}abc{cell} (B)
                //(C1){cell}123{cell} (C)
                //{table} (D)
                //surroundMacro is table, it start from the 2nd cell, its end is (C) then. as GroupProcessor construct method
                //getPreviousMacroStart() return (D) first.  Here is assume {table} macro doesn't have newline!
                //so it is safe remove all newline between (C) and (D).  
                // Then next process is (B) and (BC), next is (A) and (B1), Here is also assume {table} macro doesn't have newline.
                // The (A) is before {table} is because GroupProcessor construct method uses surrounding macro start as "end" 
                int end = gp.getMacroEnd(start);
                if (end != -1) {
                    int prevStart = gp.getPreviousMacroStart();
                    //remove all newline between end(current macro) and previous processed macro start
                    if (end <= prevStart) {
                        //if equals, means 2 group is conjunction without any character. such as {cell}{cell} - no space or any character between cell markup.
                        if (end < prevStart) {
                            sb.replace(end, prevStart,
                                    sb.subSequence(end, prevStart).toString().replaceAll("\n", ""));
                        }
                    } else {
                        AuditLogger.warn("GroupProcessor current macro end is less than last macro start:" + end
                                + ">" + start + ". Overlapped!");
                    }
                } else {
                    AuditLogger.warn("GroupProcessor doesn't find the macro end value by start " + start);
                }
            }
            //after process done, set new current macro start - where any unexpected happens, always setPreviousMacroStart to latest!
            //as insertGroupKey() will change text content.
            gp.setPreviousMacroStart(start);
            gp.insertGroupKey(start, sb);
        }
        return sb.toString();
    } else {
        return text;
    }
}