001 /*
002 * Copyright (C) 2012 eXo Platform SAS.
003 *
004 * This is free software; you can redistribute it and/or modify it
005 * under the terms of the GNU Lesser General Public License as
006 * published by the Free Software Foundation; either version 2.1 of
007 * the License, or (at your option) any later version.
008 *
009 * This software is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * You should have received a copy of the GNU Lesser General Public
015 * License along with this software; if not, write to the Free
016 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018 */
019
020 package org.crsh.util;
021
022 import java.util.ArrayList;
023 import java.util.Arrays;
024 import java.util.Iterator;
025 import java.util.List;
026 import java.util.regex.Matcher;
027 import java.util.regex.Pattern;
028
029 public class Strings {
030
031 /** . */
032 private static final Pattern p = Pattern.compile("\\S+");
033
034 public static List<String> chunks(CharSequence s) {
035 List<String> chunks = new ArrayList<String>();
036 Matcher m = p.matcher(s);
037 while (m.find()) {
038 chunks.add(m.group());
039 }
040 return chunks;
041 }
042
043 public static String join(Iterable<String> strings, String separator) {
044 Iterator<String> i = strings.iterator();
045 if (i.hasNext()) {
046 String first = i.next();
047 if (i.hasNext()) {
048 StringBuilder buf = new StringBuilder();
049 buf.append(first);
050 while (i.hasNext()) {
051 buf.append(separator);
052 buf.append(i.next());
053 }
054 return buf.toString();
055 } else {
056 return first;
057 }
058 } else {
059 return "";
060 }
061 }
062
063 /**
064 * @see #findLongestCommonPrefix(Iterable)
065 */
066 public static String findLongestCommonPrefix(CharSequence... seqs) {
067 return findLongestCommonPrefix(Arrays.asList(seqs));
068 }
069
070 /**
071 * Find the longest possible common prefix of the provided char sequence.
072 *
073 * @param seqs the sequences
074 * @return the longest possible prefix
075 */
076 public static String findLongestCommonPrefix(Iterable<? extends CharSequence> seqs) {
077 String common = "";
078 out:
079 while (true) {
080 String candidate = null;
081 for (CharSequence s : seqs) {
082 if (common.length() + 1 > s.length()) {
083 break out;
084 } else {
085 if (candidate == null) {
086 candidate = s.subSequence(0, common.length() + 1).toString();
087 } else if (s.subSequence(0, common.length() + 1).toString().equals(candidate)) {
088 // Ok it is a prefix
089 } else {
090 break out;
091 }
092 }
093 }
094 if (candidate == null) {
095 break;
096 } else {
097 common = candidate;
098 }
099 }
100 return common;
101 }
102 }