Click here to Skip to main content
15,886,038 members
Articles / Programming Languages / C#

Persistent String Parser

Rate me:
Please Sign up or sign in to vote.
4.33/5 (18 votes)
21 Dec 2008Public Domain4 min read 77.1K   382   38  
Parse a string with quoted elements, insert/add/delete elements, and is CLS compliant
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using StringParserLib;

namespace StringParserDemo
{
	public partial class Form1 : Form
	{
        StringParser parser;

        //--------------------------------------------------------------------------------
		/// <summary>
		/// Constructor
		/// </summary>
		public Form1()
		{
			InitializeComponent();
            parser                     = new StringParser();
            //editParseString.Text = "1,2,3,4";
            editParseString.Text = "1,2,3,,4,\"some,quoted,data,inside,this string\",";
            editDelimiterString.Text    = ",";
            radioDeleteFirst.Checked = true;
			editQuoteChar.Text = "\"";
			checkUseQuotes.Checked = true;

            Parse();
		}

        //--------------------------------------------------------------------------------
        /// <summary>
        /// Places the current original original parse string into the edit field.
        /// </summary>
        private void UpdateParsingString()
        {
            editParseString.Text = parser.ReassembleOriginalString();
        }

        //--------------------------------------------------------------------------------
		/// <summary>
		/// Call the parser's parsing routine and resets form fields.
		/// </summary>
        private void Parse()
        {
            if (parser != null)
            {
                string stringToParse = editParseString.Text;
                string delimiter     = editDelimiterString.Text;
                string quoteString   = editQuoteChar.Text;
                char   quoteChar     = (quoteString.Length == 0 || !checkUseQuotes.Checked) ? '\0' : quoteString[0];
                parser.ResetOriginalString(stringToParse, delimiter, quoteChar);
                listboxElements.Items.Clear();

				int count = parser.Elements.Count;
                if (count > 0)
                {
					listboxElements.Items.Add(string.Format("Reassembled\t{0}", parser.ReassembleOriginalString()));

					string tempString = "";
                    for (int i = 0; i < count; i++)
                    {
                        tempString = parser.GetField(i);
                        if (tempString.Length == 0)
                        {
                            tempString = "<NO DATA>";
                        }
                        listboxElements.Items.Add(string.Format("Index {0}\t\t{1}", i, tempString));
                    }
                }
            }
            else
            {
                MessageBox.Show("ERROR - parser object is null");
            }
        }

		//--------------------------------------------------------------------------------
		/// <summary>
		/// Fired when the Done button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void buttonDone_Click(object sender, EventArgs e)
		{
		    Close();
		}

		//--------------------------------------------------------------------------------
		/// <summary>
		/// Fired when the Parse button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void buttonParse_Click(object sender, EventArgs e)
		{
		    Parse();
		}

		//--------------------------------------------------------------------------------
		/// <summary>
		/// Fired when the "insert" Go button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void buttonInsertGo_Click(object sender, EventArgs e)
		{
		    string stringToInsert = editInsertString.Text;
		    string indexString = editInsertPos.Text;
		    if (indexString.Length == 0)
		    {
		        MessageBox.Show("You forgot to specify the insertion index.");
		        editInsertPos.Focus();
		        return;
		    }
		    int index = Convert.ToInt32(indexString);
		    parser.InsertField(index, stringToInsert);
		    UpdateParsingString();
		    Parse();
		}

		//--------------------------------------------------------------------------------
		/// <summary>
		/// Fired when the "add" Go button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void buttonAddGo_Click(object sender, EventArgs e)
		{
		    string stringToAdd = editAddString.Text;
		    parser.AddField(stringToAdd);
		    UpdateParsingString();
		    Parse();
		}

		//--------------------------------------------------------------------------------
		/// <summary>
		/// Fired when the "delete by index" Go button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void buttonDeleteByIndexGo_Click(object sender, EventArgs e)
		{
		    string indexString = editDeleteIndex.Text;
		    int index = Convert.ToInt32(indexString);

		    if (indexString.Length == 0)
		    {
		        MessageBox.Show("You forgot to specify the index to delete.");
		        editDeleteIndex.Focus();
		        return;
		    }

		    bool success = parser.DeleteField(index);
		    if (!success)
		    {
		        MessageBox.Show("ERROR - index not deleted (value out of range?)");
		    }
		    else
		    {
		        UpdateParsingString();
		        Parse();
		    }
		}

		//--------------------------------------------------------------------------------
		/// <summary>
		/// Fired when the "delete by string value" Go button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void buttonDeleteByStringGo_Click(object sender, EventArgs e)
		{
		    string stringToDelete = editDeleteString.Text;
		    bool   exactMatch     = checkExactMatch.Checked;

		    if (stringToDelete.Length == 0)
		    {
		        MessageBox.Show("You forgot to specify the string that you want to delete.");
		        editDeleteString.Focus();
		        return;
		    }

		    DeleteAction deleteAction = DeleteAction.DeleteFirst;
		    if (radioDeleteAll.Checked) 
			{
				deleteAction = DeleteAction.DeleteAll;
			}
		    if (radioDeleteFirst.Checked) 
			{
				deleteAction = DeleteAction.DeleteFirst;
			}
		    if (radioDeleteLast.Checked) 
			{
				deleteAction = DeleteAction.DeleteLast;
			}

		    bool success = parser.DeleteField(stringToDelete, exactMatch, deleteAction);
		    if (!success)
		    {
		        MessageBox.Show("ERROR - string not found");
		    }
		    else
		    {
		        UpdateParsingString();
		        Parse();
		    }
		}

	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Software Developer (Senior) Paddedwall Software
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions