Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join a string using delimiters

People also ask

How do you join two strings together?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

What is string join method?

join() method concatenates the given elements with the delimiter and returns the concatenated string. Note that if an element is null, then null is added. The join() method is included in java string since JDK 1.8.

Can a delimiter be a string?

In Java, delimiters are the characters that split (separate) the string into tokens. Java allows us to define any characters as a delimiter. There are many string split methods provides by Java that uses whitespace character as a delimiter. The whitespace delimiter is the default delimiter in Java.


It's impossible to give a truly language-agnostic answer here as different languages and platforms handle strings differently, and provide different levels of built-in support for joining lists of strings. You could take pretty much identical code in two different languages, and it would be great in one and awful in another.

In C#, you could use:

StringBuilder builder = new StringBuilder();
string delimiter = "";
foreach (string item in list)
{
    builder.Append(delimiter);
    builder.Append(item);
    delimiter = ",";       
}
return builder.ToString();

This will prepend a comma on all but the first item. Similar code would be good in Java too.

EDIT: Here's an alternative, a bit like Ian's later answer but working on a general IEnumerable<string>.

// Change to IEnumerator for the non-generic IEnumerable
using (IEnumerator<string> iterator = list.GetEnumerator())
{
    if (!iterator.MoveNext())
    {
        return "";
    }
    StringBuilder builder = new StringBuilder(iterator.Current);
    while (iterator.MoveNext())
    {
        builder.Append(delimiter);
        builder.Append(iterator.Current);
    }
    return builder.ToString();
}

EDIT nearly 5 years after the original answer...

In .NET 4, string.Join was overloaded pretty significantly. There's an overload taking IEnumerable<T> which automatically calls ToString, and there's an overload for IEnumerable<string>. So you don't need the code above any more... for .NET, anyway.


In .NET, you can use the String.Join method:

string concatenated = String.Join(",", list.ToArray());

Using .NET Reflector, we can find out how it does it:

public static unsafe string Join(string separator, string[] value, int startIndex, int count)
{
    if (separator == null)
    {
        separator = Empty;
    }
    if (value == null)
    {
        throw new ArgumentNullException("value");
    }
    if (startIndex < 0)
    {
        throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
    }
    if (count < 0)
    {
        throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
    }
    if (startIndex > (value.Length - count))
    {
        throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
    }
    if (count == 0)
    {
        return Empty;
    }
    int length = 0;
    int num2 = (startIndex + count) - 1;
    for (int i = startIndex; i <= num2; i++)
    {
        if (value[i] != null)
        {
            length += value[i].Length;
        }
    }
    length += (count - 1) * separator.Length;
    if ((length < 0) || ((length + 1) < 0))
    {
        throw new OutOfMemoryException();
    }
    if (length == 0)
    {
        return Empty;
    }
    string str = FastAllocateString(length);
    fixed (char* chRef = &str.m_firstChar)
    {
        UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
        buffer.AppendString(value[startIndex]);
        for (int j = startIndex + 1; j <= num2; j++)
        {
            buffer.AppendString(separator);
            buffer.AppendString(value[j]);
        }
    }
    return str;
}

There's little reason to make it language-agnostic when some languages provide support for this in one line, e.g., Python's

",".join(sequence)

See the join documentation for more info.


For python be sure you have a list of strings, else ','.join(x) will fail. For a safe method using 2.5+

delimiter = '","'
delimiter.join(str(a) if a else '' for a in list_object)

The "str(a) if a else ''" is good for None types otherwise str() ends up making then 'None' which isn't nice ;)


In PHP's implode():

$string = implode($delim, $array);