locked
How to check for Carriage Return of each element end in string array and add if not exists? RRS feed

  • Question

  • User339833461 posted

    I have a string array with string elements, here how to check each string element at the end contains carriage return(\n) and add if not contains at the end.

    pls help me

    Thanks

    Friday, February 28, 2020 7:37 AM

All replies

  • User753101303 posted

    Hi,

    This is homework? You could try :

    using System;
    namespace ConsoleDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                var str = new string[] { "a", "b\n", "c", "d" };
    
                for (var i = 0;i<str.Length;i++) // iterate over each array index
                {
                    if (!str[i].EndsWith("\n")) // Check if the string enfs with \n
                    {
                        str[i] += "\n"; // append extra string if not
                        
                    }
                    Console.Write(str[i]); // Not WriteLine but shown on a separate line on the console
                }
                Console.WriteLine("End"); // To check \n was appended to the last element
            }
        }
    }

    Friday, February 28, 2020 8:33 AM
  • User503812343 posted
    if(!stringVariable.Contains("\n"))
    {
      
      stringVariable = stringVariable + "\n";
    
    }

    Friday, February 28, 2020 8:34 AM