Search code examples
c#stringlistconcatenation

Removing strings from a list line by line


My question is, if I have a list that looks something like the following,

var list = new List<string>();
list.Add("12345");
list.Add("Words");
list.Add("Are");
list.Add("Here");
list.Add("13264");
list.Add("More");
list.Add("Words");
list.Add("15654");
list.Add("Extra");
list.Add("Words");

And I want to be able to delete all the strings that start with numbers from the list and also concatenate the strings in between them so that it looks like the following,

Words Are Here
More Words
Extra Words

How does that logic look? Below is what I have been trying to do, but I can't first out how to delete the strings with number much less create a newline when i delete a string with numbers.

foreach (string s in list)
        {
            if (s.StartsWith("1"))
                s.Remove(0, s.Length);
            else
                String.Concat(s);
        }

        foreach (string p in list)
            Console.WriteLine(p);

Solution

  • You could try something like:

    using System;
    using System.Collections.Generic;
                        
    public class Program
    {
        public static void Main()
        {
            var list = new List<string>();
            list.Add("12345");
            list.Add("Words");
            list.Add("Are");
            list.Add("Here");
            list.Add("13264");
            list.Add("More");
            list.Add("Words");
            list.Add("15654");
            list.Add("Extra");
            list.Add("Words");      
            
            var resultStrings = new List<string>(); 
            
            string currentString = "";
            foreach (string s in list)
            {
                if (s.StartsWith("1"))
                {               
                    resultStrings.Add(currentString);
                    currentString = "";
                }
                else
                {
                    currentString += s + " ";
                }
            }
            resultStrings.Add(currentString);
    
            foreach (string p in resultStrings)
                Console.WriteLine(p);
        }
    }
    

    basically I am looping thou the list if the value is not starting with 1 I add the value to the currentString. When the value does start with 1 we add the currentString to the resultStrings an start a new currentString.

    There are some improvements possible, the if with starts withs 1 is not completely fool prove.
    You could use int.Parse. Is multiple items in a row start with 1 you can end up with empty string in the resultStrings
    You could fix this bij checking is the string is empty before adding it to the list