Java/Data Type/String Join
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Concatenates two arrays of strings
- 2 Join an array of strings into one delimited string
- 3 Joins array elements into a single String: specify the start index and end index.
- 4 Joins array elements into a single String without specifying the start index and end index.
- 5 Joins array elements: Null objects or empty strings within the array are represented by empty strings.
- 6 Joins the elements of Collection into a single String with string separator.
- 7 Joins the elements of Iterator into a single with char value as separator.
- 8 Joins the elements of the provided array into a single String containing the provided list of elements.
- 9 Joins the elements of the provided Collection into a single String containing the provided elements.
- 10 Joins the elements of the provided Iterator into a single String containing the provided elements.
- 11 Join String
- 12 Remove/collapse multiple spaces.
- 13 Reverse the split operation.
- 14 Split and join strings
- 15 Split and join strings 2
Concatenates two arrays of strings
/*
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://wingsframework.org).
*
* wingS is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/
import java.util.StringTokenizer;
/**
* Some string manipulation utilities.
*
* @author
*/
public class StringUtil {
/**
* concatenates two arrays of strings.
*
* @param s1 the first array of strings.
* @param s2 the second array of strings.
* @return the resulting array with all strings in s1 and s2
*/
public static final String[] concat(String[] s1, String[] s2) {
String[] erg = new String[s1.length + s2.length];
System.arraycopy(s1, 0, erg, 0, s1.length);
System.arraycopy(s2, 0, erg, s1.length, s2.length);
return erg;
}
}
Join an array of strings into one delimited string
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
public class Main{
/////////////////////////////////////////////////////////////////////////
// Joining/Concatenation Methods //
/////////////////////////////////////////////////////////////////////////
/**
* Join an array of strings into one delimited string.
*
* @param buff String buffered used for join (buffer is not reset).
* @param array Array of objects to join as strings.
* @param delim Delimiter to join strings with or <i>null</i>.
* @return Joined string.
*/
public static String join(final StringBuffer buff, final Object array[],
final String delim)
{
boolean haveDelim = (delim != null);
for (int i = 0; i < array.length; i++)
{
buff.append(array[i]);
// if this is the last element then don"t append delim
if (haveDelim && (i + 1) < array.length)
{
buff.append(delim);
}
}
return buff.toString();
}
/**
* Join an array of strings into one delimited string.
*
* @param array Array of objects to join as strings.
* @param delim Delimiter to join strings with or <i>null</i>.
* @return Joined string.
*/
public static String join(final Object array[], final String delim)
{
return join(new StringBuffer(), array, delim);
}
/**
* Convert and join an array of objects into one string.
*
* @param array Array of objects to join as strings.
* @return Converted and joined objects.
*/
public static String join(final Object array[])
{
return join(array, null);
}
/**
* Convert and join an array of bytes into one string.
*
* @param array Array of objects to join as strings.
* @return Converted and joined objects.
*/
public static String join(final byte array[])
{
Byte bytes[] = new Byte[array.length];
for (int i = 0; i < bytes.length; i++)
{
bytes[i] = new Byte(array[i]);
}
return join(bytes, null);
}
/**
* Return a string composed of the given array.
*
* @param buff Buffer used to construct string value (not reset).
* @param array Array of objects.
* @param prefix String prefix.
* @param separator Element sepearator.
* @param suffix String suffix.
* @return String in the format of:
* prefix + n ( + separator + n+i)* + suffix.
*/
public static String join(final StringBuffer buff, final Object[] array,
final String prefix, final String separator,
final String suffix)
{
buff.append(prefix);
join(buff, array, separator);
buff.append(suffix);
return buff.toString();
}
/**
* Return a string composed of the given array.
*
* @param array Array of objects.
* @param prefix String prefix.
* @param separator Element sepearator.
* @param suffix String suffix.
* @return String in the format of:
* prefix + n ( + separator + n+i)* + suffix.
*/
public static String join(final Object[] array, final String prefix,
final String separator, final String suffix)
{
return join(new StringBuffer(), array, prefix, separator, suffix);
}
}
Joins array elements into a single String: specify the start index and end index.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 {
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ",") = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @param startIndex the first index to start joining from. It is
* an error to pass in an end index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, <code>null</code> if null array input
*/
public static String join(Object[] array, String separator, int startIndex, int endIndex) {
if (array == null) {
return null;
}
if (separator == null) {
separator = "";
}
// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
int bufSize = (endIndex - startIndex);
if (bufSize <= 0) {
return "";
}
bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length())
+ separator.length());
StringBuffer buf = new StringBuffer(bufSize);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
}
Joins array elements into a single String without specifying the start index and end index.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 {
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ",") = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null array input
*/
public static String join(Object[] array, String separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ",") = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @param startIndex the first index to start joining from. It is
* an error to pass in an end index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, <code>null</code> if null array input
*/
public static String join(Object[] array, String separator, int startIndex, int endIndex) {
if (array == null) {
return null;
}
if (separator == null) {
separator = "";
}
// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
int bufSize = (endIndex - startIndex);
if (bufSize <= 0) {
return "";
}
bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length())
+ separator.length());
StringBuffer buf = new StringBuffer(bufSize);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
}
Joins array elements: Null objects or empty strings within the array are represented by empty strings.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 {
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No separator is added to the joined String.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a", "b", "c"]) = "abc"
* StringUtils.join([null, "", "a"]) = "a"
* </pre>
*
* @param array the array of values to join together, may be null
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array) {
return join(array, null);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ",") = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null array input
*/
public static String join(Object[] array, String separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ",") = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @param startIndex the first index to start joining from. It is
* an error to pass in an end index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, <code>null</code> if null array input
*/
public static String join(Object[] array, String separator, int startIndex, int endIndex) {
if (array == null) {
return null;
}
if (separator == null) {
separator = "";
}
// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
int bufSize = (endIndex - startIndex);
if (bufSize <= 0) {
return "";
}
bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length())
+ separator.length());
StringBuffer buf = new StringBuffer(bufSize);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
}
Joins the elements of Collection into a single String with string separator.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.Collection;
import java.util.Iterator;
import java.util.List;
public class Main {
/**
* <p>Joins the elements of the provided <code>Collection</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param collection the <code>Collection</code> of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null iterator input
* @since 2.3
*/
public static String join(Collection collection, String separator) {
if (collection == null) {
return null;
}
return join(collection.iterator(), separator);
}
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterator the <code>Iterator</code> of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null iterator input
*/
public static String join(Iterator iterator, String separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return "";
}
Object first = iterator.next();
if (!iterator.hasNext()) {
return toString(first);
}
// two or more elements
StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
// ToString
//-----------------------------------------------------------------------
/**
* <p>Gets the <code>toString</code> of an <code>Object</code> returning
* an empty string ("") if <code>null</code> input.</p>
*
* <pre>
* ObjectUtils.toString(null) = ""
* ObjectUtils.toString("") = ""
* ObjectUtils.toString("bat") = "bat"
* ObjectUtils.toString(Boolean.TRUE) = "true"
* </pre>
*
* @see StringUtils#defaultString(String)
* @see String#valueOf(Object)
* @param obj the Object to <code>toString</code>, may be null
* @return the passed in Object"s toString, or nullStr if <code>null</code> input
* @since 2.0
*/
public static String toString(Object obj) {
return obj == null ? "" : obj.toString();
}
}
Joins the elements of Iterator into a single with char value as separator.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.Iterator;
import java.util.List;
public class Main {
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterator the <code>Iterator</code> of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null iterator input
* @since 2.0
*/
public static String join(Iterator iterator, char separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return "";
}
Object first = iterator.next();
if (!iterator.hasNext()) {
return toString(first);
}
// two or more elements
StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
buf.append(separator);
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
// ToString
//-----------------------------------------------------------------------
/**
* <p>Gets the <code>toString</code> of an <code>Object</code> returning
* an empty string ("") if <code>null</code> input.</p>
*
* <pre>
* ObjectUtils.toString(null) = ""
* ObjectUtils.toString("") = ""
* ObjectUtils.toString("bat") = "bat"
* ObjectUtils.toString(Boolean.TRUE) = "true"
* </pre>
*
* @see StringUtils#defaultString(String)
* @see String#valueOf(Object)
* @param obj the Object to <code>toString</code>, may be null
* @return the passed in Object"s toString, or nullStr if <code>null</code> input
* @since 2.0
*/
public static String toString(Object obj) {
return obj == null ? "" : obj.toString();
}
}
Joins the elements of the provided array into a single String containing the provided list of elements.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 {
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ";") = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ";") = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array, char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ";") = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ";") = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @param startIndex the first index to start joining from. It is
* an error to pass in an end index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, <code>null</code> if null array input
* @since 2.0
*/
public static String join(Object[] array, char separator, int startIndex, int endIndex) {
if (array == null) {
return null;
}
int bufSize = (endIndex - startIndex);
if (bufSize <= 0) {
return "";
}
bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1);
StringBuffer buf = new StringBuffer(bufSize);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
}
Joins the elements of the provided Collection into a single String containing the provided elements.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.Collection;
import java.util.Iterator;
import java.util.List;
public class Main {
/**
* <p>Joins the elements of the provided <code>Collection</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param collection the <code>Collection</code> of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null iterator input
* @since 2.3
*/
public static String join(Collection collection, char separator) {
if (collection == null) {
return null;
}
return join(collection.iterator(), separator);
}
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterator the <code>Iterator</code> of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, <code>null</code> if null iterator input
* @since 2.0
*/
public static String join(Iterator iterator, char separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return "";
}
Object first = iterator.next();
if (!iterator.hasNext()) {
return toString(first);
}
// two or more elements
StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
buf.append(separator);
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
// ToString
//-----------------------------------------------------------------------
/**
* <p>Gets the <code>toString</code> of an <code>Object</code> returning
* an empty string ("") if <code>null</code> input.</p>
*
* <pre>
* ObjectUtils.toString(null) = ""
* ObjectUtils.toString("") = ""
* ObjectUtils.toString("bat") = "bat"
* ObjectUtils.toString(Boolean.TRUE) = "true"
* </pre>
*
* @see StringUtils#defaultString(String)
* @see String#valueOf(Object)
* @param obj the Object to <code>toString</code>, may be null
* @return the passed in Object"s toString, or nullStr if <code>null</code> input
* @since 2.0
*/
public static String toString(Object obj) {
return obj == null ? "" : obj.toString();
}
}
Joins the elements of the provided Iterator into a single String containing the provided elements.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.Iterator;
import java.util.List;
public class Main {
/**
* <p>Joins the elements of the provided <code>Iterator</code> into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A <code>null</code> separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterator the <code>Iterator</code> of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, <code>null</code> if null iterator input
*/
public static String join(Iterator iterator, String separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return "";
}
Object first = iterator.next();
if (!iterator.hasNext()) {
return toString(first);
}
// two or more elements
StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
// ToString
//-----------------------------------------------------------------------
/**
* <p>Gets the <code>toString</code> of an <code>Object</code> returning
* an empty string ("") if <code>null</code> input.</p>
*
* <pre>
* ObjectUtils.toString(null) = ""
* ObjectUtils.toString("") = ""
* ObjectUtils.toString("bat") = "bat"
* ObjectUtils.toString(Boolean.TRUE) = "true"
* </pre>
*
* @see StringUtils#defaultString(String)
* @see String#valueOf(Object)
* @param obj the Object to <code>toString</code>, may be null
* @return the passed in Object"s toString, or nullStr if <code>null</code> input
* @since 2.0
*/
public static String toString(Object obj) {
return obj == null ? "" : obj.toString();
}
}
Join String
/*
* Static String formatting and query routines.
* Copyright (C) 2001-2005 Stephen Ostermiller
* http://ostermiller.org/contact.pl?regarding=Java+Utilities
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See COPYING.TXT for details.
*/
import java.util.HashMap;
import java.util.regex.Pattern;
/**
* Utilities for String formatting, manipulation, and queries.
* More information about this class is available from .
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.00.00
*/
public class StringHelper {
/**
* Join all the elements of a string array into a single
* String.
* <p>
* If the given array empty an empty string
* will be returned. Null elements of the array are allowed
* and will be treated like empty Strings.
*
* @param array Array to be joined into a string.
* @return Concatenation of all the elements of the given array.
* @throws NullPointerException if array is null.
*
* @since ostermillerutils 1.05.00
*/
public static String join(String[] array){
return join(array, "");
}
/**
* Join all the elements of a string array into a single
* String.
* <p>
* If the given array empty an empty string
* will be returned. Null elements of the array are allowed
* and will be treated like empty Strings.
*
* @param array Array to be joined into a string.
* @param delimiter String to place between array elements.
* @return Concatenation of all the elements of the given array with the the delimiter in between.
* @throws NullPointerException if array or delimiter is null.
*
* @since ostermillerutils 1.05.00
*/
public static String join(String[] array, String delimiter){
// Cache the length of the delimiter
// has the side effect of throwing a NullPointerException if
// the delimiter is null.
int delimiterLength = delimiter.length();
// Nothing in the array return empty string
// has the side effect of throwing a NullPointerException if
// the array is null.
if (array.length == 0) return "";
// Only one thing in the array, return it.
if (array.length == 1){
if (array[0] == null) return "";
return array[0];
}
// Make a pass through and determine the size
// of the resulting string.
int length = 0;
for (int i=0; i<array.length; i++){
if (array[i] != null) length+=array[i].length();
if (i<array.length-1) length+=delimiterLength;
}
// Make a second pass through and concatenate everything
// into a string buffer.
StringBuffer result = new StringBuffer(length);
for (int i=0; i<array.length; i++){
if (array[i] != null) result.append(array[i]);
if (i<array.length-1) result.append(delimiter);
}
return result.toString();
}
}
Remove/collapse multiple spaces.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
*
* @author
* @version $Id: StringUtils.java 685685 2008-08-13 21:43:27Z nbubna $
*/
public class Main {
/**
* Remove/collapse multiple spaces.
*
* @param argStr string to remove multiple spaces from.
* @return String
*/
public static String collapseSpaces(String argStr)
{
char last = argStr.charAt(0);
StringBuffer argBuf = new StringBuffer();
for (int cIdx = 0 ; cIdx < argStr.length(); cIdx++)
{
char ch = argStr.charAt(cIdx);
if (ch != " " || last != " ")
{
argBuf.append(ch);
last = ch;
}
}
return argBuf.toString();
}
}
Reverse the split operation.
import java.util.Collection;
import java.util.Iterator;
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/util/branches/sakai_2-5-4/util-util/util/src/java/org/sakaiproject/util/StringUtil.java $
* $Id: StringUtil.java 34934 2007-09-10 22:52:23Z lance@indiana.edu $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.
*
**********************************************************************************/
/**
* <p>
* StringUtil collects together some string utility classes.
* </p>
*/
public class StringUtil
{
/**
* Reverse the split operation.
*
* @param parts
* The parts to combine
* @param index
* the index to the fist part to use
* @param length
* the number of parts to use
* @param splitter
* The between-parts text
*/
public static String unsplit(String[] parts, int index, int length, String splitter)
{
if (parts == null) return null;
if ((index < 0) || (index >= parts.length)) return null;
if (index+length > parts.length) return null;
StringBuilder buf = new StringBuilder();
for (int i = index; i < index+length; i++)
{
if (parts[i] != null) buf.append(parts[i]);
buf.append(splitter);
}
// remove the trailing splitter
buf.setLength(buf.length()-splitter.length());
return buf.toString();
}
}
Split and join strings
/*
* Copyright (C) 2001-2003 Colin Bell
* colbell@users.sourceforge.net
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.util.ArrayList;
import java.util.List;
/**
* String handling utilities.
*
* @author
*/
public class StringUtilities
{
/**
* Return <tt>true</tt> if the passed string is <tt>null</tt> or empty.
*
* @param str String to be tested.
*
* @return <tt>true</tt> if the passed string is <tt>null</tt> or empty.
*/
public static boolean isEmpty(String str)
{
return str == null || str.length() == 0;
}
/**
* Return whether the 2 passed strings are equal. This function
* allows for <TT>null</TT> strings. If <TT>s1</TT> and <TT>s1</TT> are
* both <TT>null</TT> they are considered equal.
*
* @param str1 First string to check.
* @param str2 Second string to check.
*/
public static boolean areStringsEqual(String str1, String str2)
{
if (str1 == null && str2 == null)
{
return true;
}
if (str1 != null)
{
return str1.equals(str2);
}
return str2.equals(str1);
}
/**
* Clean the passed string. Replace whitespace characters with a single
* space. If a <TT>null</TT> string passed return an empty string. E.G.
* replace
*
* [pre]
* \t\tselect\t* from\t\ttab01
* [/pre]
*
* with
*
* [pre]
* select * from tab01
* [/pre]
*
* @param str String to be cleaned.
*
* @return Cleaned string.
*/
public static String cleanString(String str)
{
final StringBuffer buf = new StringBuffer(str.length());
char prevCh = " ";
for (int i = 0, limit = str.length(); i < limit; ++i)
{
char ch = str.charAt(i);
if (Character.isWhitespace(ch))
{
if (!Character.isWhitespace(prevCh))
{
buf.append(" ");
}
}
else
{
buf.append(ch);
}
prevCh = ch;
}
return buf.toString();
}
/**
* Return the number of occurences of a character in a string.
*
* @param str The string to check.
* @param ch The character check for.
*
* @return The number of times <tt>ch</tt> occurs in <tt>str</tt>.
*/
public static int countOccurences(String str, int ch)
{
if (isEmpty(str))
{
return 0;
}
int count = 0;
int idx = -1;
do
{
idx = str.indexOf(ch, ++idx);
if (idx != -1)
{
++count;
}
}
while (idx != -1);
return count;
}
/**
* Split a string based on the given delimiter, but don"t remove
* empty elements.
*
* @param str The string to be split.
* @param delimiter Split string based on this delimiter.
*
* @return Array of split strings. Guaranteeded to be not null.
*/
public static String[] split(String str, char delimiter)
{
return split(str, delimiter, false);
}
/**
* Split a string based on the given delimiter, optionally removing
* empty elements.
*
* @param str The string to be split.
* @param delimiter Split string based on this delimiter.
* @param removeEmpty If <tt>true</tt> then remove empty elements.
*
* @return Array of split strings. Guaranteeded to be not null.
*/
public static String[] split(String str, char delimiter,
boolean removeEmpty)
{
// Return empty list if source string is empty.
final int len = (str == null) ? 0 : str.length();
if (len == 0)
{
return new String[0];
}
final List<String> result = new ArrayList<String>();
String elem = null;
int i = 0, j = 0;
while (j != -1 && j < len)
{
j = str.indexOf(delimiter,i);
elem = (j != -1) ? str.substring(i, j) : str.substring(i);
i = j + 1;
if (!removeEmpty || !(elem == null || elem.length() == 0))
{
result.add(elem);
}
}
return result.toArray(new String[result.size()]);
}
/**
* Joins the specified parts separating each from one another with the
* specified delimiter. If delim is null, then this merely returns the
* concatenation of all the parts.
*
* @param parts the strings to be joined
* @param delim the char(s) that should separate the parts in the result
* @return a string representing the joined parts.
*/
public static String join(String[] parts, String delim) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
String part = parts[i];
result.append(part);
if (delim != null && i < parts.length-1) {
result.append(delim);
}
}
return result.toString();
}
public static String[] segment(String source, int maxSegmentSize) {
ArrayList<String> tmp = new ArrayList<String>();
if (source.length() <= maxSegmentSize) {
return new String[] { source };
}
boolean done = false;
int currBeginIdx = 0;
int currEndIdx = maxSegmentSize;
while (!done) {
String segment = source.substring(currBeginIdx, currEndIdx);
tmp.add(segment);
if (currEndIdx >= source.length()) {
done = true;
continue;
}
currBeginIdx = currEndIdx;
currEndIdx += maxSegmentSize;
if (currEndIdx > source.length()) {
currEndIdx = source.length();
}
}
return tmp.toArray(new String[tmp.size()]);
}
public static int getTokenBeginIndex(String selectSQL, String token)
{
String lowerSel = selectSQL.toLowerCase();
String lowerToken = token.toLowerCase().trim();
int curPos = 0;
int count = 0;
while(-1 != curPos)
{
curPos = lowerSel.indexOf(lowerToken, curPos + lowerToken.length());
if(-1 < curPos
&& (0 == curPos || Character.isWhitespace(lowerSel.charAt(curPos-1)))
&& (lowerSel.length() == curPos + lowerToken.length() || Character.isWhitespace(lowerSel.charAt(curPos + lowerToken.length())))
)
{
return curPos;
}
// If we"ve loop through one time for each character in the string,
// then something must be wrong. Get out!
if (count++ > selectSQL.length()) {
break;
}
}
return curPos;
}
public static Byte[] getByteArray(byte[] bytes) {
if (bytes == null || bytes.length == 0 ) {
return new Byte[0];
}
Byte[] result = new Byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
result[i] = Byte.valueOf(bytes[i]);
}
return result;
}
/**
* Chops off the very last character of the given string.
*
* @param aString a string to chop
* @return the specified string minus it"s last character, or null for null
* or empty string for a string with length == 0|1.
*/
public static String chop(String aString) {
if (aString == null) {
return null;
}
if (aString.length() == 0) {
return "";
}
if (aString.length() == 1) {
return "";
}
return aString.substring(0, aString.length()-1);
}
/**
* Returns the platform-specific line separator, or "\n" if it is not defined for some reason.
*
* @return the platform-specific line separator.
*/
public static String getEolStr() {
return System.getProperty("line.separator", "\n");
}
}
Split and join strings 2
import java.awt.FontMetrics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* Globally available utility classes, mostly for string manipulation.
*
* @author Jim Menard,
*/
public class StringUtils {
protected static final int DEFAULT_MAX_MESSAGE_WIDTH = 78;
/**
* Returns a list of substrings created by splitting the given string at the
* given delimiter. The return value will be <code>null</code> if the string
* is <code>null</code>, else it will be a non-empty list of strings. If
* <var>delim</var> is <code>null</code> or is not found in the string, the
* list will contain one element: the original string.
* <p>
* This isn"t the same thing as using a tokenizer. <var>delim</var> is a
* literal string, not a set of characters any of which may be a delimiter.
*
* @param str
* the string we"re splitting
* @param delim
* the delimter string
*/
public static List split(String str, String delim) {
if (str == null)
return null;
ArrayList list = new ArrayList();
if (delim == null) {
list.add(str);
return list;
}
int subStart, afterDelim = 0;
int delimLength = delim.length();
while ((subStart = str.indexOf(delim, afterDelim)) != -1) {
list.add(str.substring(afterDelim, subStart));
afterDelim = subStart + delimLength;
}
if (afterDelim <= str.length())
list.add(str.substring(afterDelim));
return list;
}
/**
* Returns a string consisting of all members of a collection separated by the
* specified string. The <code>toString</code> method of each collection
* member is called to convert it to a string.
*
* @param c
* a collection of objects
* @param joinWith
* the string that will separate each member of the collection
*/
public static String join(Collection c, String joinWith) {
if (c == null)
return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator iter = c.iterator(); iter.hasNext();) {
if (first)
first = false;
else if (joinWith != null)
buf.append(joinWith);
buf.append(iter.next().toString());
}
return buf.toString();
}
/**
* Returns an array of strings, one for each line in the string. Lines end
* with any of cr, lf, or cr lf. A line ending at the end of the string will
* not output a further, empty string.
* <p>
* This code assumes <var>str</var> is not <code>null</code>.
*
* @param str
* the string to split
* @return a non-empty list of strings
*/
public static List splitIntoLines(String str) {
ArrayList strings = new ArrayList();
int len = str.length();
if (len == 0) {
strings.add("");
return strings;
}
int lineStart = 0;
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
if (c == "\r") {
int newlineLength = 1;
if ((i + 1) < len && str.charAt(i + 1) == "\n")
newlineLength = 2;
strings.add(str.substring(lineStart, i));
lineStart = i + newlineLength;
if (newlineLength == 2) // skip \n next time through loop
++i;
} else if (c == "\n") {
strings.add(str.substring(lineStart, i));
lineStart = i + 1;
}
}
if (lineStart < len)
strings.add(str.substring(lineStart));
return strings;
}
/**
* Appends a string to a string buffer, adding extra newlines so the message
* is not too wide. Max width is not guaranteed; if there is no space in a
* line before <code>DEFAULT_MAX_MESSAGE_WIDTH</code> then the next one
* after it will be used insetead. Each line will be trimmed before and after
* it"s added, so some whitespace may be goofed up. This is used for error
* message wrapping, so it"s not critical that whitespace be preserved.
* <p>
* TODO Looks for space, not all whitespace. This should probably change.
*
* @param buf
* the string buffer
* @param str
* the string
*/
public static void splitUp(StringBuffer buf, String str) {
splitUp(buf, str, DEFAULT_MAX_MESSAGE_WIDTH);
}
/**
* Appends a string to a string buffer, adding extra newlines so the message
* is not too wide. Max width is not guaranteed; if there is no space in a
* line before <var>maxWidth</var> then the next one after it will be used
* instead. Each line will be trimmed before and after it"s added, so some
* whitespace may be goofed up. This is used for error message wrapping, so
* it"s not critical that whitespace be preserved.
* <p>
* TODO Looks for space, not all whitespace. This should probably change.
*
* @param buf
* the string buffer
* @param str
* the string
* @param maxWidth
* maximum number of chars in each line
*/
public static void splitUp(StringBuffer buf, String str, int maxWidth) {
if (str == null)
return;
str = str.trim();
while (str.length() >= maxWidth) {
int pos = str.lastIndexOf(" ", maxWidth);
if (pos == -1) { // No spaces before; look for first one after
pos = str.indexOf(" ", maxWidth);
if (pos == -1)
break;
}
buf.append(str.substring(0, pos).trim());
buf.append("\n");
str = str.substring(pos + 1).trim();
}
buf.append(str);
}
}