c# – 替换第二次出现?与 &
发布时间:2020-12-15 23:43:25 所属栏目:百科 来源:网络整理
导读:任何人都可以提供相应的代码来替换“?”的第二个实例在带有“”的字符串中? 我环顾四周但看起来似乎并没有这样做,而且我开始时并没有使用正则表达式. 谢谢 解决方法 您可以使用IndexOf指定起始索引来查找第二个问号的索引,然后使用Substring: var index =
任何人都可以提供相应的代码来替换“?”的第二个实例在带有“&”的字符串中?
我环顾四周但看起来似乎并没有这样做,而且我开始时并没有使用正则表达式. 谢谢 解决方法
您可以使用IndexOf指定起始索引来查找第二个问号的索引,然后使用Substring:
var index = input.IndexOf('?',input.IndexOf('?') + 1); var ouput = string.Concat(input.Substring(0,index),"&",input.Substring(index + 1)); 要么: var output = new string(input.Select((c,i) => i == index ? '&' : c).ToArray()); 您还可以编写扩展方法: public static string ReplaceWith( this string source,char charToReplace,int index) { if(source == null) throw new ArgumentNullException("source"); if (index == -1) return source; var output = new char[source.Length]; for (int i = 0; i < source.Length; i++) { if (i != index) output[i] = source[i]; else output[i] = charToReplace; } return new string(output); } 然后使用它: var index = input.IndexOf('?',input.IndexOf('?') + 1); var output = input.ReplaceWith('&',index); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |