Ravinder Godara
Ravinder Godara

Reputation: 15

Set brackets before and after on every word in c#

I'm trying to set curly brackets'{}' before and after on every word in string. for eg. Hello everyone, is this my string. and i want to change it into {Hello} {everyone}, {is} {this} {my} {string}.. For this purpose i split words using below code:

string a="Hello everyone is this my string.";
string[] words=a.Split(' ');
for(int i=0; i<words.Length; i++)
{
a=a.Replace(words[i],"{"+words[i]+"}");
}

code is working good but this replace is into this. and i got output like this {Hello} {everyone}, {is} th{is} {my} {string}. How to solve this problem. Thanks in advance.

Upvotes: 0

Views: 409

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18153

The reason for the particular behavior is the following line.

a=a.Replace(words[i],"{"+words[i]+"}");

String.Replace will replace all the occurrence of the particular string. So when you attempt to replace is, you would end up replacing the is substring in this as well.

You could do the following for getting the correct result.

var originalString ="Hello everyone is this my string.";
var words= Regex.Replace(originalString,@"\b[^ ]+\b",@"{$0}");

This would ensure the period character is taken care of as in the desired answer in OP.

Samples

Hello everyone is this my string.
{Hello} {everyone} {is} {this} {my} {string}.
Hello everyone, is this my string.
{Hello} {everyone}, {is} {this} {my} {string}.

Upvotes: 3

Related Questions