Bhavya

Code -> Break -> Fix -> Blog

String replace C# (without using built IN methods)

1 Comment

1. Simple replace:

public static string MyReplaceSimple(this string source, string oldValue, string newValue)
 {
 if (source != null)
 {
 var sourceArr = source.Split(new[] { oldValue }, StringSplitOptions.None);

 var result = new StringBuilder();

 for (int i = 0; i < sourceArr.Length; i++)
 {
 result.Append(sourceArr[i]);

 if (i + 1 != sourceArr.Length)
 {
 result.Append(newValue);
 }
 }

 return result.ToString();
 }
 return null;
 }

2. Replace using LINQ:

public static string MyReplaceLinq(this string source, string oldValue, string newValue)
 {
 if (source != null)
 {
 var sourceArr = source.Split(new[] { oldValue }, StringSplitOptions.None);
 var start = sourceArr.Take(1);
 var end =
 from originalString in sourceArr.Skip(1)
 from newString in new[] { newValue, originalString }
 select newString;
 var result = String.Join("", start.Concat(end));
 return result;
 }

 return null;
 }

Happy coding…

~BS

Advertisements

One thought on “String replace C# (without using built IN methods)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s