How to replace a character in a string without using the replace()method?

Posted by Tanwar18 under C# on 3/19/2012 | Points: 10 | Views : 1306 | Status : [Member] | Replies : 7
How to replace a character in a string without using the replace()method?
like
String ab= "hellohello";
String bc= "ll";
String cd= "ss";
The output should be "hessohesso" after printing the variable ab without using replace() method on console. Can anybody help me?




Responses

Posted by: Rajni.Shekhar on: 3/20/2012 [Member] Bronze | Points: 25

Up
0
Down
string[] arrS = ab.Split('l');
arrS[1] = cd;
arrS[3] = cd;
string s = string.Empty;
for (int i = 0; i < arrS.Length; i++)
{

s = s+arrS[i];
}
Response.Write(s);


This code can be work and there are many more methods like concatenate and join can be used to get the output string.

Thanks,
Rajni Shekhar

Tanwar18, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tanwar18 on: 3/20/2012 [Member] Starter | Points: 25

Up
0
Down
thanks but it's not working

Tanwar18, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ndebata on: 3/20/2012 [Member] Starter | Points: 25

Up
0
Down
Hi

Take a look at the bellow code
String ab = "hellohello";

String bc = "ll";
String cd = "ss";

var _matches = System.Text.RegularExpressions.Regex.Matches(ab, bc);
foreach (System.Text.RegularExpressions.Match item in _matches)
{
ab=ab.Remove(item.Index, item.Length);
ab=ab.Insert(item.Index, cd);
}

Console.Write(ab);


Tanwar18, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tanwar18 on: 3/20/2012 [Member] Starter | Points: 25

Up
0
Down
bingo! thanks. complex but effective..

Tanwar18, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sksamantaray on: 3/20/2012 [Member] Silver | Points: 25

Up
0
Down
Hi Ndebta,
good one.

Thanks,
Sanjay

Tanwar18, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajni.Shekhar on: 3/20/2012 [Member] Bronze | Points: 25

Up
0
Down
Hi Ndebata,
Really good one, using regular expression it can be possible.

Thanks,
Rajni Shekhar

Tanwar18, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sksamantaray on: 3/20/2012 [Member] Silver | Points: 25

Up
0
Down
Hi Another way without String.Replace

using System.Text.RegularExpressions;

String ab = "hellohello";
String bc = "ll";
String cd = "ss";
string result =
Regex.Replace(ab, bc, cd, RegexOptions.IgnoreCase);
Response.Write(result);


Thanks,
Sanjay

Tanwar18, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response