Barnabeck
Barnabeck

Reputation: 481

Substring build in iteration loop based on delimiters

I'm pretty new to C# and having trouble.

I have this string with a '/'- delimiter: "1/2/10/4"

The string I need to use while I'm iterating through the loop should look like this:

i = 1; "1"
i = 2; "1/2"
i = 3; "1/2/10"
i = 4; "1/2/10/4"  

Somehow it should be integrated here, but I don't know how:

        var IDArray = Convert.ToString(NodesID).Split('/');
        for (int i = 0; i < Convert.ToString(NodesID).Count(x => x == '/')+2; i++)
        {
            string IDCheck = IDArray[i];
            string ???
        }

Upvotes: 2

Views: 116

Answers (3)

displayName
displayName

Reputation: 14389

var IDArray = Convert.ToString(NodesID).Split('/');
var builder = new StringBuilder();
for (int i = 0; i < IDArray.Length; i++)
{
    builder.Append(IDArray[i]);
    var stringToUse = builder.ToString();

    //...
    //Use the stringToUse here. It contains exactly what you want.
    //...

    builder.Append("/");
}

Everything is self-explanatory. Let me know if there's something you didn't quite understand (or if I failed to correctly interpret your question).

Upvotes: 1

Me.Name
Me.Name

Reputation: 12544

Not exactly the most readable code, but a linqy solution would be:

var list = YourInput.Split('/').Aggregate(new List<string>(), (l, el) => { l.Add(l.Count == 0 ? el : l[l.Count - 1] + "/" + el); return l; });

This would create a list with the strings.

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156624

I would recommend using a helper method that will yield all of the subpaths you're looking for. Something like this should work:

public IEnumerable<string> GetSubPaths(string s)
{
    var sb = new StringBuilder();
    for(int i = 0; i < s.Length; s++)
    {
        if(s[i] == '\\')
            yield return sb.ToString();
        sb.Append(s[i]);
    }
    yield return sb.ToString();
}

This method uses a C# trick called yield return which causes it to return an IEnumerable<> where each element is based on what's provided to yield return. So the elements in this returned IEnumerable<> will represent each substring group that you're describing.

Then you can use the results from this method however you want:

var subPaths = GetSubPaths("1/2/10/4").ToList();
for(int i = 0; i < subPaths.Count; i++)
{
    Console.Write("i = " + i + "; ");
    Console.WriteLine(subPaths[i]);
}

Upvotes: 0

Related Questions