0

What is the efficient way to parse through a large delimited string so that I can access just one element from the delimited set without having to store the other substrings involved?

example string: "1,2,3,4,....,21,22,23,24" and my goal is to extract just the element 22 without having to store the rest of the numbers as done when using the Split() method.

Not a duplicate of this.

Not a duplicate of the one suggested either. In my case, I am particularly looking for an exact element in a finite string. This is much different to the other case where they try to extract the first few occurrences from an infinitely long string. My problem seems much simpler. I don't want to store any extra tokens/array elements other than the one element I am interested in.

re3el
  • 735
  • 2
  • 12
  • 28
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/186950/discussion-on-question-by-re3el-c-effficient-way-to-extract-an-item-from-a-str). – Samuel Liew Jan 19 '19 at 02:43

2 Answers2

0

I made a quick algo for your example. Index is zero-based, so you should pass 0 in case you need the first item. You can change the delimeter char or provide it as an argument.

Short explanation: we iterate over the all chars of a string and skip all items until we get into requested one. After that, we find the next delimeter and return a part of a whole string or return the rest of the string if we don't find any delimeters.

public static string GetItemByIndex(string line, int index)
{
    for (var i = 0; i < line.Length; i++)
    {
        if (index == 0)
        {
            for (int j = i; j < line.Length; j++)
            {
                if (line[j] == ',')
                {
                    return line.Substring(i, j - i);
                }
            }

            return line.Substring(i, line.Length - i);
        }

        if (line[i] == ',' && index != 0)
        {
            index--;
        }
    }

    return null;
}
opewix
  • 4,993
  • 1
  • 20
  • 42
0

This could be a possible solution:

    public static string GetValue(string myString,int position)
    {
        return myString.Split(',')[position - 1];
    }

    static void Main(string[] args)
    {
        string myItem = "22";
        Console.WriteLine(GetValue("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27", 22));
        Console.ReadLine();  
    }  
Alex Leo
  • 2,781
  • 2
  • 13
  • 29