Remove and Add comma in String at Dynamic way

195 Views Asked by At

I have address separated by comma like address1,address2,city,country I need to remove comma if the any of value is empty or null at run time.

1

There are 1 best solutions below

0
Vonkel. On

Basic method, but i think you could make better if you search

string mee = "address1,,city,country";
        string[] arr = mee.Split(',');
        string final = string.Empty;
        for (int i = 0; i < arr.Length; i++)
        {                
            if (string.IsNullOrEmpty(arr[i]))
                continue;

            final += i == 0 ? arr[i] : $",{arr[i]}";

        }

Or perhaps with System.Linq (but you must test all possibilities)

            string final = String.Join(",", mee.Split(',').Where((x) => !string.IsNullOrEmpty(x)));