001/* 002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library 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 * Contributors: 015 * bstefanescu 016 */ 017package org.nuxeo.shell.utils; 018 019import java.util.ArrayList; 020import java.util.List; 021 022/** 023 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 024 */ 025public class StringUtils { 026 027 public static String join(String[] ar, String delim) { 028 if (ar == null || ar.length == 0) { 029 return ""; 030 } 031 if (ar.length == 1) { 032 return ar[0]; 033 } 034 StringBuilder buf = new StringBuilder(); 035 buf.append(ar[0]); 036 for (int i = 1; i < ar.length; i++) { 037 buf.append(delim).append(ar[i]); 038 } 039 return buf.toString(); 040 } 041 042 public static String join(List<String> ar, String delim) { 043 return join(ar.toArray(new String[ar.size()]), delim); 044 } 045 046 public static String[] split(String str, char delimiter, boolean trim) { 047 int s = 0; 048 int e = str.indexOf(delimiter, s); 049 if (e == -1) { 050 if (trim) { 051 str = str.trim(); 052 } 053 return new String[] { str }; 054 } 055 List<String> ar = new ArrayList<String>(); 056 do { 057 String segment = str.substring(s, e); 058 if (trim) { 059 segment = segment.trim(); 060 } 061 ar.add(segment); 062 s = e + 1; 063 e = str.indexOf(delimiter, s); 064 } while (e != -1); 065 066 int len = str.length(); 067 if (s < len) { 068 String segment = str.substring(s); 069 if (trim) { 070 segment = segment.trim(); 071 } 072 ar.add(segment); 073 } else { 074 ar.add(""); 075 } 076 077 return ar.toArray(new String[ar.size()]); 078 } 079 080}