sunboy_sunboy
sunboy_sunboy

Reputation: 263

How can I replace comma instead of some phrases?

I have a string of characters that starts with a space and has \r\n,I want to delete the first space and delete \r\n then replace it with a comma after the word if there is a space?

My String : "\r\n ram\r\ncomputer\r\n" ....

I want the following mode to change? laptop,computer,ram

Upvotes: 0

Views: 697

Answers (2)

Rajesh G
Rajesh G

Reputation: 637

As per @valuator answer you can use Trim() to remove trailing spaces. And to address other concerns pointed out in comments, you can use regex replace as below.

string myString = " laptop  computer ram";
var rx= new Regex(@"[\s]+");
myString= rx.Replace(myString.Trim(), ",");

the regex [\s]+ will match any whitespace characters

Upvotes: 1

Valuator
Valuator

Reputation: 3617

Use Trim() to remove the space at the beginning (and/or end) and then Replace() to replace the space between words with commas.

https://learn.microsoft.com/en-us/dotnet/api/system.string.trim?view=net-6.0

https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=net-6.0

string myString = " laptop computer ram";
string newString = myString.Trim().Replace(' ', ',');

Upvotes: 0

Related Questions