开发者

Remove extra commas in C#

开发者 https://www.devze.com 2023-01-30 09:26 出处:网络
I have a string like \"abc,,bcd,\"; The output should be abc,bcd i.e. the extra commas should be removed.

I have a string like "abc,,bcd,";

The output should be abc,bcd i.e. the extra commas should be removed.

Help needed开发者_Go百科


string result = Regex.Replace(input, ",+", ",").Trim(',');


How about something like

string s = "abc,,bcd,";
s = s.Trim(',');
while (s.Contains(",,"))
    s = s.Replace(",,", ",");


string input = "abc,,bcd,";
string output = String.Join(",",
    input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
);


You can try splitting the string into an array. Then loop through the array. Check if the current element has a value you find acceptable. Append that value to a stringbuilder. If that is not the last element of the array, append a comma to the stringbuilder.


string input = "abc,,bcd,";

input.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Aggregate((a, b) => a + "," + b);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号