Is it possible to replace commas and spaces with commas in c#? I'm fresh in c# and am looking for guidance.
Any help is appreciated!

Before:
Deleting 11 files.ABC: Total Time = 01:16:30, Remaining Time = 00:00:00

After:

Deleting,11,files,ABC: Total,Time,01:16:30,Remaining,Time,00:00:00

Recommended Answers

All 5 Replies

How to replaces spaces, full stops and commas*

string before = "Deleting 11 files.ABC: Total Time = 01:16:30, Remaining Time = 00:00:00";
string after = Regex.Replace( before, @"[,= ]", "" );

Don't really need to use Regex, String.Replace will work fine :)

string newString = "Deleting 11 files.ABC: Total Time = 01:16:30, Remaining Time = 00:00:00".Replace(' ', ',').Replace('.', ',');

Using regex does look tidier although the one listed above is incorrect. It should be:
string newString = Regex.Replace("Deleting 11 files.ABC: Total Time = 01:16:30, Remaining Time = 00:00:00", @"[\.\s+]", ",");
Note that the full-stop has to be escaped as it is a regex token and 's' is escaped as it indicates a "space", the + sign means "any number of" in this case.

You could also use Aggregate:

string oldString =  "Deleting 11 files.ABC: Total Time = 01:16:30, Remaining Time = 00:00:00";
char[] replace = new char[] { '.', ' ' };
string newString = replace.Aggregate(oldString, (prev, next) => prev.Replace(next, ','));

Hi
could you kindly explain what goes in here for my understanding?

@"[,= ]", "" 

That regex string would match ',', '=' and ' ' and remove them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.