Sunday 20 September 2015

Create a custom Paragraph class and Iterate the elements from paragraph based on settings like Letter,Word,Line, EachParagraph

In this post we are going to see create a custom paragraph class and Iterate the elements from the objects based on the settings like Word, Letter, Line, Each Paragraph.

i.e While passing the Object we will get the iteration as  Letter, Word, Line, EachParagraph based on the settings. 
For example, We are going to do the sample like below which will give the output in foreach as Based on the settings for that object.


Paragraph para = "This a good book ,   Every one wants to read it.\n\nThis book deals with                     technology.   ";


Iteration Sample 1:

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.EachParagraph;
            
            foreach (var item in para)
            {
                Console.WriteLine(item);

            }


Output:
****************************
This a good book ,   Every one wants to read it.
This book deals with technology.



Iteration Sample 2: 

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Line;

            foreach (var item in para)
            {
                Console.WriteLine(item);
            }


Output:
****************************
This a good book ,   Every one wants to read it.

This book deals with technology.



Iteration Sample 3: 

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Word;

            foreach (var item in para)
            {
                Console.WriteLine(item);
            }


Output:
****************************
This
a
good
book
,


Every
one
wants
to
read
it.

This
book
deals
with
technology.


Iteration Sample 4: 
            
            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Letter;

            foreach (var item in para)
            {
                Console.WriteLine(item);
            }


Output:
****************************
T
h
i
etc ... Remaining letters are print in screen based on the settings.


From the above sample you can see that an string is assigned to a class variable, then we are assign a iteration settings based on that settings , when we pass variable in foreach it will give the result like Lettter, Word, Line, EachParagraph.

Let we see now how we can do like this class and make the iteration differ based on the settings.
In this sample we have to create following file and class.

1. Paragraph
2. ParagraphIterationContainer
3. AbstractIterator
4. LetterIterator
5. LineIterator
6. WordIterater
7. ParagraphIterator

Enum

1. IterationSettings
2. ParagraphComparison
3. ParaIterationType


Paragraph.cs


using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace StringExtensions
{      
    public sealed class Paragraph
      : IComparable, IComparable<Paragraph>, IEnumerable<string>,
IEnumerable, IEquatable<Paragraph>, ICloneable,IConvertible
    {

        private string value;

        public ParaIterationType IterationType
        {
            set;
            get;
        }

        public IterationSettings IterationSettings
        {
            set;
            get;
        }

        public string Content { get { return value; } }
               
        public Paragraph(string value):this(value,ParaIterationType.Word){  }

public Paragraph(string value,ParaIterationType iterationType)    
             :this(value,iterationType,IterationSettings.None){  }

        public Paragraph(string value,ParaIterationType iterationType,IterationSettings
iterationSettings)
        {
            this.value = value;
            this.IterationType = iterationType;
            this.IterationSettings = iterationSettings;
        }

        public int CompareTo(object para2)
        {
            if (para2 == null)
                return 1;
           
            if (!(para2 is Paragraph))
            {
                throw new ArgumentException("Input is not a Paragraph type");
            }

            return Paragraph.Compare(this, (Paragraph)value,
ParagraphComparison.CurrentCulture);
        }

        public int CompareTo(Paragraph para2)
        {
            if (para2 == null)
                return 1;
            return Paragraph.Compare(this, para2, ParagraphComparison.CurrentCulture);
        }

public static int Compare(Paragraph paragraph1, Paragraph paragraph2,
ParagraphComparison comparisonType)
        {
            if (comparisonType > ParagraphComparison.OrdinalIgnoreCase)
            {
                throw new ArgumentException("Not supported comparison type");
            }

            if (paragraph1 == paragraph2)
                return 0;
            if (paragraph1 == null)
                return -1;
            if (paragraph2 == null)
                return 1;
            switch (comparisonType)
            {            
                case ParagraphComparison.CurrentCulture:
                    return CultureInfo.CurrentCulture.CompareInfo.Compare( 
paragraph1.value, paragraph2.value, CompareOptions.None);
                case ParagraphComparison.CurrentCultureIgnoreCase:
                    return CultureInfo.CurrentCulture.CompareInfo.Compare(
paragraph1.value, paragraph2.value, CompareOptions.IgnoreCase);
                case ParagraphComparison.InvariantCulture:
                    return CultureInfo.InvariantCulture.CompareInfo.Compare(
paragraph1.value, paragraph2.value, CompareOptions.None);
                case ParagraphComparison.InvariantCultureIgnoreCase:
                    return CultureInfo.InvariantCulture.CompareInfo.Compare(
paragraph1.value, paragraph2.value, CompareOptions.IgnoreCase);               
                default:
                  throw new NotSupportedException("Not supported Paragraph comparison");
            }

        }
       
        public static implicit operator Paragraph(string value)
        {
            if (value == null)
                value = string.Empty;

            return new Paragraph(value);
        }
       
        public IEnumerator<string> GetEnumerator()
        {
            return ParagraphIterationContainer.GetIterator(this);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public bool Equals(Paragraph other)
        {
            return other.Content == this.Content;
        }

        public object Clone()
        {
            return new Paragraph(this.Content,IterationType,IterationSettings);
        }
      
        public TypeCode GetTypeCode()
        {
            return TypeCode.String;
        }

        public bool ToBoolean(IFormatProvider provider)
        {
            return Convert.ToBoolean(this.Content, provider);
        }

        public byte ToByte(IFormatProvider provider)
        {
            return Convert.ToByte(this.Content, provider);
        }

        public char ToChar(IFormatProvider provider)
        {
            return Convert.ToChar(this.Content, provider);
        }

        public DateTime ToDateTime(IFormatProvider provider)
        {
            return Convert.ToDateTime(this.Content, provider);
        }

        public decimal ToDecimal(IFormatProvider provider)
        {
            return Convert.ToDecimal(this.Content, provider);
        }

        public double ToDouble(IFormatProvider provider)
        {
            return Convert.ToDouble(this.Content, provider);
        }

        public short ToInt16(IFormatProvider provider)
        {
            return Convert.ToInt16(this.Content, provider);
        }

        public int ToInt32(IFormatProvider provider)
        {
            return Convert.ToInt32(this.Content, provider);
        }

        public long ToInt64(IFormatProvider provider)
        {
            return Convert.ToInt64(this.Content, provider);
        }

        public sbyte ToSByte(IFormatProvider provider)
        {
            return Convert.ToSByte(this.Content, provider);
        }

        public float ToSingle(IFormatProvider provider)
        {
            return Convert.ToSingle(this.Content, provider);
        }

        public string ToString(IFormatProvider provider)
        {
            return this.Content;
        }

        public object ToType(Type conversionType, IFormatProvider provider)
        {
            return this.ToString(provider);
        }

        public ushort ToUInt16(IFormatProvider provider)
        {
            return Convert.ToUInt16(this.Content, provider);
        }

        public uint ToUInt32(IFormatProvider provider)
        {
            return Convert.ToUInt32(this.Content, provider);
        }

        public ulong ToUInt64(IFormatProvider provider)
        {
            return Convert.ToUInt64(this.Content, provider);
        }

        private class ParagraphIterationContainer
        {
            public static AbstractIterator GetIterator(Paragraph doc)
            {
                AbstractIterator Iterator = null;

                switch (doc.IterationType)
                {
                    case ParaIterationType.Word:
                        Iterator = new WordIterater(doc);
                        break;
                    case ParaIterationType.Letter:
                        Iterator = new LetterIterator(doc);
                        break;
                    case ParaIterationType.Line:
                        Iterator = new LineIterator(doc);
                        break;
                    case ParaIterationType.EachParagraph:
                        Iterator = new ParagraphIterator(doc);
                        break;
                    default:
                        break;
                }
                return Iterator;
            }
        }

    }
   
}



2. AbstractIterator

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringExtensions
{
    public abstract class AbstractIterator:IEnumerator<string>
    {
        protected int currentPos = -1;
        protected int startPos = -1;
        protected int endPos = -1;

        protected ParaIterationType _iterationType;
        protected Paragraph _doc;
        protected int _docLength;

        protected AbstractIterator(ParaIterationType iterationtype,Paragraph value)
        {
            this._iterationType = iterationtype;
            this._doc = value;
            this._docLength = this._doc.Content.Length;
        }

        public string Current
        {
            get
            {
                startPos = endPos;
                return GetCurrentItem();
            }
        }

        public void Dispose()
        {
            _doc = null;
            _docLength = -1;
        }

        object IEnumerator.Current
        {
            get
            {
                startPos = endPos;
                return GetCurrentItem();
            }
        }

        public bool MoveNext()
        {
            if (currentPos < _docLength-1)
                return true;
            else
                return false;
        }

        public void Reset()
        {
            currentPos = startPos = endPos = -1;
        }

       public abstract string GetCurrentItem();

    }
}



3. LetterIterator

   public class LetterIterator:AbstractIterator
    {
        public LetterIterator(Paragraph doc):base(ParaIterationType.Letter,doc)
        {

        }

        public override string GetCurrentItem()
        {                      
            currentPos = startPos + 1;
            endPos = startPos + 1;
            return _doc.Content[startPos + 1].ToString();           
        }
    }


4. WordIterater


public class WordIterater:AbstractIterator
    {
        public WordIterater(Paragraph doc):base(ParaIterationType.Word,doc)
        {

        }

        public override string GetCurrentItem()
        {           
            return FindNextWord(startPos + 1);
        }

        private string FindNextWord(int index)
        {
            string _word = string.Empty;
            for (int i = index; i < _docLength; i++)
            {
                currentPos = i;
                if (_doc.Content[i] == ' ')
                {
                    endPos = i;
                    break;
                }
                _word = _word + _doc.Content[i];
            }

            //if (index < _docLength)
            //{
            //    if (this._doc.IterationSettings ==
IterationSettings.IgnoreSpace && _word.Trim() == string.Empty)
            //        return Current;
            //}

            return _word;
        }


    }



5. LineIterator

    public class LineIterator:AbstractIterator
    {
        public LineIterator(Paragraph doc):base(ParaIterationType.Line,doc)
        {

        }

        public override string GetCurrentItem()
        {
            return FindNextLine(startPos+1);           
        }

        private string FindNextLine(int index)
        {
            string _word = string.Empty;
            for (int i = index; i < _docLength; i++)
            {
                currentPos = i;
                if (_doc.Content[i] == '\n')
                {
                    endPos = i;
                    break;
                }
                _word = _word + _doc.Content[i];
            }
            return _word;
        }

    }


6. ParagraphIterator

public class ParagraphIterator:AbstractIterator
    {
        public ParagraphIterator(Paragraph doc):base(ParaIterationType.EachParagraph,doc)
        {

        }

        public override string GetCurrentItem()
        {
            string _word = string.Empty;
            bool firstNewline = false;
            bool newParagraphIndication = false;

            for (int i = startPos+1; i < _docLength; i++)
            {
                currentPos = i;
                if (_doc.Content[i] == '\n')
                {

                    if (!firstNewline)
                    {
                        firstNewline = true;
                        continue;
                    }
                    else
                        newParagraphIndication = true;

                    if (newParagraphIndication)
                    {
                        endPos = i;
                        break;
                    }
                }
                _word = _word + _doc.Content[i];
            }
            return _word;
        }

    }





public enum IterationSettings
    {
        None,
        IgnoreSpace,
        IgnoreNewLine,
        IgnoreTabSpace,
        IgnoreCarriageReturn,
        IgnoreAllSpaces = IgnoreSpace | IgnoreTabSpace,
        IgonreAll = IgnoreCarriageReturn | IgnoreNewLine | IgnoreAllSpaces
    }


    public enum ParagraphComparison
    {
        CurrentCulture,
        CurrentCultureIgnoreCase,
        InvariantCulture,
        InvariantCultureIgnoreCase,
        Ordinal,
        OrdinalIgnoreCase
    }

   public enum ParaIterationType
    {
        Word,
        Letter,
        Line,
        EachParagraph
    }


Now let we see how to see the Paragraph class.


Program.cs


    class Program
    {
        static void Main(string[] args)
        {
            Paragraph para = "This a good book ,   Every one wants to read it.\n\nThis book 
                              deals with technology.   ";

            para.IterationType = ParaIterationType.EachParagraph;

            Console.WriteLine("\n****************************");
            foreach (var item in para)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Line;
            foreach (var item in para)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Word;
            foreach (var item in para)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\n****************************");
            para.IterationType = ParaIterationType.Letter;
            foreach (var item in para)
            {
                Console.WriteLine(item);
            }



            Console.Read();

        }
    }


Output:










  


From this post you can understand that how to create a class like paragraph and change the iteration based on the settings.

No comments:

Post a Comment