vfioox
vfioox

Reputation: 738

Foreach each element, but they may repeat

I have an array of tags that may appear in console as color tags. There's 37 of them.

So, I do this code:

tagsCT is a string[]

foreach (string tag in tagsCT)
{
    if (text.Contains(tag))
    {
    ArrayList x = new ArrayList();
    x.Add(tag);
    x.Add(tagsColorValues[k]);
    tagss.Add(text.IndexOf(tag));
    tags.Add(text.IndexOf(tag) - 1, x);
    }
k++;
}

What do I have: text = "2013-11-11 17:56:14 [INFO] $4/time: $5Changes the time on each world" What I need to do is find all the color tags in the string. All the possible ones are in an array string[]

tagsCT = { "$1","$2","$3","$4" }

I show it as an example, but the tags aren't always the same length. But the problem strikes in these situations:

text = "2013-11-11 17:56:14 [INFO] $4/time: $5Changes the time on each $4world"

The last tag will not be detected. The question is how to prevent it.

Upvotes: 1

Views: 140

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460238

You could use a Dictionary<string, IList<int>> instead:

var tagIndices = new Dictionary<string,  IList<int>>();
foreach (string tag in tagsCT)
{
    IList<int> indices;
    if (tagIndices.TryGetValue(tag, out indices))
        continue; // to prevent the same indices on duplicate tags, you could also use a HashSet<string> instead of the array
    else
    {
        indices = new List<int>();
        tagIndices.Add(tag, indices);
    }
    int index = text.IndexOf(tag);
    while (index >= 0)
    {
        indices.Add(index);
        index = text.IndexOf(tag, index + 1);
    }
}

Each tag is stored as key and the value is the list of indices (can be empty).

Here's a demonstration

Upvotes: 2

David Libido
David Libido

Reputation: 479

How about, after you've processed the tag, remove it from the "text" string? You could also use a for(int i;;i) structure using the IndexOf value. (sorry, where the hell is he comment button then?)

Upvotes: 1

Related Questions