替换字符串中最后一次出现的单词 - c#
我有一个问题,我需要替换字符串中最后一次出现的单词。替换字符串中最后一次出现的单词 - c#
情况:我给出一个字符串,格式如下:
string filePath ="F:/jan11/MFrame/Templates/feb11";
我那么喜欢这个替换TnaName
:
filePath = filePath.Replace(TnaName, ""); //feb11 is TnaName
这工作,但我有一个问题,当TnaName
与我的folder name
相同。当发生这种情况我最终得到的字符串是这样的:
F:/feb11/MFrame/Templates/feb11
现在,它已经取代了TnaName
两次出现与feb11
。有没有一种方法可以替换我的字符串中单词的最后一次出现?谢谢。
注意:feb11
是TnaName
来自另一个进程 - 这不是问题。
这里是替换字符串
public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
int place = Source.LastIndexOf(Find);
if(place == -1)
return Source;
string result = Source.Remove(place, Find.Length).Insert(place, Replace);
return result;
}
-
Source
是要做手术的字符串最后一次出现的功能。 -
Find
是您要替换的字符串。 -
Replace
是您要替换的字符串。
+1我喜欢你的更好:) – 2013-02-12 05:37:35
**比我的.... – 2013-02-12 05:43:46
非常感谢泛型function.Its工作,我也同意@Simon。 – 2013-02-12 05:46:56
使用string.LastIndexOf()
查找最后一次出现的字符串的索引,然后使用子串查找您的解决方案。
你要做的手动替换:
int i = filePath.LastIndexOf(TnaName);
if (i >= 0)
filePath = filePath.Substring(0, i) + filePath.Substring(i + TnaName.Length);
您可以使用Path
类从System.IO
namepace:
string filePath = "F:/jan11/MFrame/Templates/feb11";
Console.WriteLine(System.IO.Path.GetDirectoryName(filePath));
我不明白为什么正则表达式不能使用:
public static string RegexReplace(this string source, string pattern, string replacement)
{
return Regex.Replace(source,pattern, replacement);
}
public static string ReplaceEnd(this string source, string value, string replacement)
{
return RegexReplace(source, $"{value}$", replacement);
}
public static string RemoveEnd(this string source, string value)
{
return ReplaceEnd(source, value, string.Empty);
}
用法:
string filePath ="F:/feb11/MFrame/Templates/feb11";
filePath = filePath.RemoveEnd("feb11"); // F:/feb11/MFrame/Templates/
filePath = filePath.ReplaceEnd("feb11","jan11"); // F:/feb11/MFrame/Templates/jan11
你应该使用Regex .Escape()的值。 – jcox 2017-11-09 19:06:18
你的意思是,'return Regex.Replace(Regex.Replace(source),pattern,replacement);'? – toddmo 2017-11-14 18:04:42
假设有人调用ReplaceEnd(“(foobar)”,“)”,thenewend) 。你的函数会抛出,因为“)$”是一个无效的正则表达式。这将工作:返回RegexReplace(源,Regex.Escape(值)+“$”,替换);同样的故事为您的RemoveEnd。 – jcox 2017-11-15 15:44:31
您的唯一目标是取代路径的最后部分? (也就是从'/开始?) – 2013-02-12 05:26:39
不是最后一部分只会修改最后一个'TnaName',这里有更多的路径,但我只生成问题的示例。谢谢。 – 2013-02-12 05:28:35
这个字符串总是通向某个东西的路径吗?如果是,请考虑使用System.IO.Path类。 – 2013-02-12 05:32:56