Parse a string to get the list of numbers (e.g."1-10, 25, 36-78") Used mainly for parsing days - CSharp System

CSharp examples for System:String Parse

Description

Parse a string to get the list of numbers (e.g."1-10, 25, 36-78") Used mainly for parsing days

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from  w w  w.  j  a v  a2s.  c  om

public class Main{
        /// <summary>
        /// Parse a string to get the list of numbers (e.g."1-10, 25, 36-78")
        /// Used mainly for parsing days
        /// </summary>
        /// <param name="dayString"></param>
        /// <param name="delimiter"></param>
        /// <returns></returns>
        public static List<int> GetNumsFromString(string dayString, char delimiter)
        {
            dayString.Replace(" ", "");
            List<int> dayList = new List<int>();
            string[] daySet = dayString.Split(delimiter);
            foreach (string days in daySet)
            {
                if (!days.Contains("-"))  //A single day
                {
                    dayList.Add(Int32.Parse(days));
                }
                else    //A day period
                {
                    string[] ds = days.Split('-');
                    int dayStart = Int32.Parse(ds.First());
                    int dayEnd = Int32.Parse(ds.Last());
                    for (int i = dayStart; i <= dayEnd; i++)
                    {
                        dayList.Add(i);
                    }
                }
            }

            return dayList;
        }
}

Related Tutorials