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

An Object-oriented Approach to Finite State Automata

Rate me:
Please Sign up or sign in to vote.
4.85/5 (19 votes)
3 Feb 2009CPOL7 min read 61.7K   1.1K   55  
A brief introduction to FSA and a ready-to-use class library
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace FSA
{
	public class ParsingAutomaton : FiniteStateAutomaton
	{
		private ParsingState[] states;

		public ParsingAutomaton(ParsingState[] states)
		{
			this.states = states;
		}
		public override void Reset()
		{
			CurrentState = 0;
		}
		public override int Send(int input)
		{
			return Send(input.ToString());
		}
		public int Send(string token)
		{
			ParsingState currentState = states[CurrentState];
			foreach (var pair in currentState.Expressions) {
				if (Regex.IsMatch(token, pair.Key)) {
					CurrentState = pair.Value;
					return states[CurrentState].Output;
				}
			}

			CurrentState = currentState.EmptyTransition;
			return states[CurrentState].Output;			
		}
		public int Send(char token)
		{
			foreach (var pair in states[CurrentState].SpecificCharacters) {
				if (token.Equals(pair.Key)) {
					CurrentState = pair.Value;
					return states[CurrentState].Output;
				}
			}
			return Send(token.ToString());
		}
		public override FiniteStateAutomaton ShallowCopy()
		{
			ParsingAutomaton copy = new ParsingAutomaton(states);
			return copy;
		}
	}
	public enum ParseCases
	{
		
	}
}

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 The Code Project Open License (CPOL)


Written By
Software Developer
Poland Poland
My name is Jacek. Currently, I am a Java/kotlin developer. I like C# and Monthy Python's sense of humour.

Comments and Discussions