Pages

Wednesday, August 15, 2007

Splitting Strings without Regex

I have this string that I want to parse the server name out of. It looks like \\server-name\printer-name\. This turns out to be a piece of cake in C#, even without Regular Expressions. Here's the code.

 private void button1_Click(object sender, EventArgs e)
  {
      string[] parsed;
      parsed = textBox1.Text.Split(textBox2.Text[0]);
      listBox1.Items.Clear();
      if (parsed.Length == 4)
      {
          listBox1.Items.AddRange(parsed);
      }
      else
      { listBox1.Items.Add(parsed.Length.ToString() + " items found"); }      
  }
What happens here is that if the string conforms to the pattern \\server\printer, then it parses into the string array parsed. Here are some examples of how it works:

Easy, huh!

No comments:

Share This!

Contact Us

Name

Email *

Message *