001/*
002 * (C) Copyright 2006-2010 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 */
019package org.nuxeo.shell.utils;
020
021import java.util.ArrayList;
022import java.util.List;
023
024/**
025 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
026 */
027public class StringUtils {
028
029    public static String join(String[] ar, String delim) {
030        if (ar == null || ar.length == 0) {
031            return "";
032        }
033        if (ar.length == 1) {
034            return ar[0];
035        }
036        StringBuilder buf = new StringBuilder();
037        buf.append(ar[0]);
038        for (int i = 1; i < ar.length; i++) {
039            buf.append(delim).append(ar[i]);
040        }
041        return buf.toString();
042    }
043
044    public static String join(List<String> ar, String delim) {
045        return join(ar.toArray(new String[ar.size()]), delim);
046    }
047
048    public static String[] split(String str, char delimiter, boolean trim) {
049        int s = 0;
050        int e = str.indexOf(delimiter, s);
051        if (e == -1) {
052            if (trim) {
053                str = str.trim();
054            }
055            return new String[] { str };
056        }
057        List<String> ar = new ArrayList<String>();
058        do {
059            String segment = str.substring(s, e);
060            if (trim) {
061                segment = segment.trim();
062            }
063            ar.add(segment);
064            s = e + 1;
065            e = str.indexOf(delimiter, s);
066        } while (e != -1);
067
068        int len = str.length();
069        if (s < len) {
070            String segment = str.substring(s);
071            if (trim) {
072                segment = segment.trim();
073            }
074            ar.add(segment);
075        } else {
076            ar.add("");
077        }
078
079        return ar.toArray(new String[ar.size()]);
080    }
081
082}