-3

I have used a timer to run through a string, I have used a while too but I am wondering is there a faster way. I have string that contains date serial number, the date is always after the text d|

private void Timer1_Tick(object sender, EventArgs e)
{
    string caldata = textBox6.Text;
    textBox7.Text = caldata.Length.ToString();

    if (caldata.Substring(0, 2) == "d|")
    {
        // MessageBox.Show("Found date" + caldata.Substring(2, 5));
        listBox1.Items.Add(caldata.Substring(2, 5));

        textBox6.Text = caldata.Remove(0, 7);
        caldata = textBox6.Text;
    }
    else
    {
        textBox6.Text = caldata.Remove(0, 1);
        caldata = textBox6.Text;
    }


    if (caldata.Length < 4)
    {
        timer1.Enabled = false;
    }
}

My string that contains the data looks like the attached.

Liam
  • 27,717
  • 28
  • 128
  • 190

2 Answers2

1

Generally, your problem could be solved with careful debugging and stepping through the code.

Anyway, below is my suggestion:

You could use regular expressions: (?<=d\|)\d{5}

Explanation:

(?<=d\|) - positive lookbeihnd: assert what preceds is d\|

\d{5} - match 5 digits

Code sample

  string caldata = "";
  MatchCollection matches = Regex.Matches(caldata, @"(?<=d\|)\d{5}");
  foreach (Match match in matches)
  {
    string txt = match.Value;
    // ... do smoething with text
  }
Gönnhardt
  • 13
  • 3
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
0

Remove and Substring are pretty slow string operations, if you want to extract data from a string you should try to find only that and not remove the irrelevant data around it.

Regex seems to be the way go here, in this case "(?!d\|)\d{5}" should be the fastest.

So your code would look like this:

var matches = Regex.Matches(caldata, @"(?!d\|)\d{5}");
foreach(Match m in matches)
{
  listbox1.Items.Add(m.Value);
}
Gönnhardt
  • 13
  • 3