Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The splitting of a string without using String.Split method does not return correct result

Tags:

string

c#

split

I want to split a string without using the String.Split method.
I found a possible solution here. The code that I use is from the second answer.
This is my code:

public string[] SplitString(string input, char delimiter)
{
    List<String> parts = new List<String>();
    StringBuilder buff = new StringBuilder();

    for (int i = 0; i < input.Length; i++)
    {
        if (input[i] == delimiter)
        {
            parts.Add(buff.ToString());
            buff.Clear();
        }
        else
        {
            buff.Append(input[i]);
        }
    }
    return parts.ToArray();
}

My problem here is that when I try to split a string like this
dog cat car person by " ", the result contains the words without the last one (in this example - person).
If after the last word there is a white space, the result is correct.

I tried to add something like i == input.Length when the for loop is from 0 to i <= input.Length. But the result was still without the last word.
Am I missing something?

like image 918
Sisi Avatar asked Feb 02 '26 22:02

Sisi


1 Answers

Add another parts.Add(buff.ToString()); after exiting the loop - to flush the last word into the collection. You can check the length before doing so or not as commented and explained why by @hvd.

if(buff.Length != 0)
{
    parts.Add(buff.ToString());
}
return parts.ToArray();

Another approach, instead of using a StringBuilder would be:

public static string[] SplitString(string input, char delimiter)
{
    List<String> parts = new List<String>();
    int start = 0;
    for(int i = 0; i < input.Length; i++)
    {
        if(input[i] == delimiter)
        {
            parts.Add(input.Substring(start, i - start));
            start = i + 1;
        }
    }
    parts.Add(input.Substring(start, input.Length - start));
    return parts.ToArray();
}

Or use yield return and return IEnumerable<string>:

public static IEnumerable<string> SplitString(string input, char delimiter)
{
    int start = 0;
    for(int i = 0; i < input.Length; i++)
    {
        if(input[i] == delimiter)
        {
            yield return input.Substring(start, i - start);
            start = i + 1;
        }
    }
    yield return input.Substring(start, input.Length - start);
}
like image 176
Gilad Green Avatar answered Feb 05 '26 13:02

Gilad Green