Implementing stuff function in C #

I need to know if C # has any function equal to sql stuff functions that replace the input string with the original string based on the start and length.

Edited to add a sample:

 select stuff('sad',1,1'b') select stuff(original string, start point, length,input string) 

the output will be "bad".

+8
c # tsql
source share
4 answers

Use the String.Insert () function and with the String.Remove () function

 "abc".Remove(1, 1).Insert(2, "XYZ") // result "aXYZc" 
+6
source share

There is no built-in method for this, but you can write an extension method:

 static class StringExtensions { public static string Splice(this string str, int start, int length, string replacement) { return str.Substring(0, start) + replacement + str.Substring(start + length); } } 

Usage is as follows:

 string sad = "sad"; string bad = sad.Splice(0, 1, "b"); 

Note that the first character in a string in C # is number 0, not 1, as in your SQL example.

If you want, you can call the Stuff method, of course, but perhaps the name Splice little clearer (although it is not used very often).

+6
source share

You can make an extension method that combines string.replace and string.insert

 public static string Stuff(this string str, int start , int length , string replaceWith_expression) { return str.Remove(start, length).Insert(start, replaceWith_expression); } 
+1
source share

There is no such function in C #, but you can write it easily. Please note that my implementation is based on zero (the first character has index 0):

 string input = "abcdefg"; int start = 2; int length = 3; string replaceWith = "ijklmn"; string stuffedString = input.Remove(start, length).Insert(start, replaceWith); // will return abijklmnfg 

You can also write an extension method that simplifies the use of the function:

 public static class StringExtensions { public static string Stuff(this string input, int start, int length, string replaceWith) { return input.Remove(start, length).Insert(start, replaceWith); } } 

Using:

 string stuffed = "abcdefg".Stuff(2, 3, "ijklmn"); 
0
source share

All Articles