在c#中的东西函数实现

我需要知道c#是否有任何函数等于sql函数的stuff ,它根据给定的开始和长度将输入字符串替换为原始字符串。

编辑添加样本:

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

输出会"bad".

没有内置方法可以执行此操作,但您可以编写扩展方法:

 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); } } 

用法如下:

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

请注意,C#中字符串中的第一个字符是数字0,而不是SQL示例中的1。

如果你愿意,你当然可以调用方法Stuff ,但可以说Splice名字更清晰一点(虽然它也没有经常使用)。

使用String.Insert()函数和String.Remove()函数

 "abc".Remove(1, 1).Insert(2, "XYZ") // result "aXYZc" 

您可以创建一个组合string.replacestring.insert的扩展方法

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

C#中没有这样的function,但您可以轻松编写。 请注意,我的实现是从零开始的(第一个字符有索引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 

您还可以编写扩展方法,这样可以更轻松地使用该函数:

 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); } } 

用法:

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

以Thorarin为例,该函数将处理超出范围的输入和空字符串。

  ///  /// combines 2 strings by inserting the replacement string into the original /// string starting at the start position and will remove up to CharsToRemove /// from the original string before appending the remainder. ///  /// original string to modify /// starting point for insertion, 0-based /// number of characters from original string to remove /// string to insert /// a new string as follows: /// {original,0,start}{replacement}{original,start+charstoremove,end} ///  ///  /// "ABC".Split(1,1,"123") == "A123C" ///  public static string Splice(this string original, int start, int charstoremove, string replacement) { // protect from null reference exceptions if (original == null) original = ""; if (replacement == null) replacement = ""; var sb = new StringBuilder(); if (start < 0) start = 0; // start is too big, concatenate strings if (start >= original.Length) { sb.Append(original); sb.Append(replacement); return sb.ToString(); } // take first piece + replacement sb.Append(original.Substring(0, start)); sb.Append(replacement); // if new length is bigger then old length, return what we have if (start+charstoremove >= original.Length) return sb.ToString(); // otherwise append remainder sb.Append(original.Substring(start + charstoremove)); return sb.ToString(); }