C# – Splitting CSV/ Looping

This is a quick example of how to split a string into a string array and how to loop through the results. We then combine the results again changing the delimiter.

        static void Main(string[] args)
        {
            string strToSplit = "TEST|TEST1|TEST2|TEST3";

            //Split the string into an Array
            string[] array = strToSplit.Split('|');

            //Loop through and write each value to the console
            foreach (string field in array)
            {
                Console.WriteLine(field);
            }

            //Combine values back changing the delimiter to a comma
            string newStr = string.Join(",", array);

            Console.WriteLine(newStr);

            //Use read to keep window open
            Console.Read();

        }

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *