C#实现的ReplaceFirst和ReplaceLast
原文:C#实现的ReplaceFirst和ReplaceLast
ReplaceFirst:
public static string ReplaceFirst(string input, string oldValue, string newValue)
{
Regex regEx = new Regex(oldValue, RegexOptions.Multiline);
return regEx.Replace(input, newValue==null?"":newValue, 1);
}
注意:如果替换的旧值中有特殊符号,替换将会失败,解决办法 例如特殊符号是“(”: 要在调用本方法前加oldValue=oldValue.Replace("(","//(");
ReplaceLast:
public static string ReplaceLast(string input, string oldValue, string newValue)
{
int index = input.LastIndexOf(oldValue);
if (index < 0)
{
return input;
}
else
{
StringBuilder sb = new StringBuilder(input.Length - oldValue.Length + newValue.Length);
sb.Append(input.Substring(0, index));
sb.Append(newValue);
sb.Append(input.Substring(index + oldValue.Length,
input.Length - index - oldValue.Length));
return sb.ToString();
}
}
最新文章
- Sublime中Markdown的安装与使用
- mysql中常用的控制流函数
- Oracle基础和用户管理
- 设置arc/非arc
- Core love JavaScript
- Unity光照图UV显示
- 关于dialog引起的 java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView not attached to window manager 错误的分析
- os8 location authorization 错误.
- 由MyEclipse内存不足谈谈JVM内存设置
- Winform获取当前程序名称或路径
- javascript中的==与===
- Maven服务器
- loadrunner脚本函数讲解
- vs 为什么使用#include ";stdafx.h";
- C#导入c++ dll报找不到dll文件 masm32调用c++类库
- Java入门系列 Java 中的四种引用
- Matlab入门笔记(1)
- print()与println()区别
- myeclipse debug模式 报错source not found
- checkbox选中事件