Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
42 views
in Technique[技术] by (71.8m points)

c# - Remove and Add comma in String at Dynamic way

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.

question from:https://stackoverflow.com/questions/65645998/remove-and-add-comma-in-string-at-dynamic-way

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...