Frank Bryce
Frank Bryce

Reputation: 8446

Split string and keeping the delimiter without Regex C#

Problem: spending too much time solving simple problems. Oh, here's the simple problem.

Example 1:

Example 2:

Solution with Regex: here

I want to avoid using Regex, simply because this requires only character comparison. It's algorithmically just as complex to do as what string.Split() does. It bothers me that I cannot find a more succinct way to do what I want.

My bad solution, which doesn't work for me... it should be faster and more succinct.

var outStr = inStr.Split(new[]{delimiter}, 
                         StringSplitOptions.RemoveEmptyEntries)
                  .Select(x => x + delimiter).ToArray();
if (inStr.Last() != delimiter) {
    var lastOutStr = outStr.Last();
    outStr[outStr.Length-1] = lastOutStr.Substring(0, lastOutStr.Length-1);
}

Upvotes: 0

Views: 830

Answers (3)

Vahid Borandeh
Vahid Borandeh

Reputation: 41

public static IEnumerable<string> SplitAndKeep(this string s, string[] delims)
    {
        int start = 0, index;
        string selectedSeperator = null;
        while ((index = s.IndexOfAny(delims, start, out selectedSeperator)) != -1)
        {
            if (selectedSeperator == null)
                continue;
            if (index - start > 0)
                yield return s.Substring(start, index - start);
            yield return s.Substring(index, selectedSeperator.Length);
            start = index + selectedSeperator.Length;
        }

        if (start < s.Length)
        {
            yield return s.Substring(start);
        }
    }

Upvotes: 0

TVOHM
TVOHM

Reputation: 2742

Using LINQ:

string input = "my,string,separated,by,commas";
string[] groups = input.Split(',');
string[] output = groups
    .Select((x, idx) => x + (idx < groups.Length - 1 ? "," : string.Empty))
    .Where(x => x != "")
    .ToArray();

Split the string into groups, then transform every group that is not the last element by appending a comma to it.

Just thought of another way you could do it, but I don't think this method is as clear:

string[] output = (input + ',').Split( new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
    .Select(x => x + ',').ToArray();

Upvotes: 2

Camilo Terevinto
Camilo Terevinto

Reputation: 32058

Seems pretty simple to me without using Regex:

string inStr = "dasdasdas";
char delimiter = 'A';
string[] result = inStr.Split(new string[] { inStr }, System.StringSplitOptions.RemoveEmptyEntries);
string lastItem = result[result.Length - 1];
int amountOfLoops = lastItem[lastItem.Length - 1] == delimiter ? result.Length - 1 : result.Length - 2;
for (int i = 0; i < amountOfLoops; i++)
{
    result[i] += delimiter;
}

Upvotes: 0

Related Questions