2013-02-12 176 views
55

我有一個問題,我需要替換字符串中最後一次出現的單詞。替換字符串中最後一次出現的單詞 - 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。有沒有一種方法可以替換我的字符串中單詞的最後一次出現?謝謝。

注意:feb11TnaName來自另一個進程 - 這不是問題。

+0

您的唯一目標是取代路徑的最後部分? (也就是從'/開始?) – 2013-02-12 05:26:39

+0

不是最後一部分只會修改最後一個'TnaName',這裏有更多的路徑,但我只生成問題的示例。謝謝。 – 2013-02-12 05:28:35

+1

這個字符串總是通向某個東西的路徑嗎?如果是,請考慮使用System.IO.Path類。 – 2013-02-12 05:32:56

回答

108

這裏是替換字符串

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

+1我喜歡你的更好:) – 2013-02-12 05:37:35

+1

**比我的.... – 2013-02-12 05:43:46

+0

非常感謝泛型function.Its工作,我也同意@Simon。 – 2013-02-12 05:46:56

10

使用string.LastIndexOf()查找最後一次出現的字符串的索引,然後使用子串查找您的解決方案。

6

你要做的手動替換:

int i = filePath.LastIndexOf(TnaName); 
if (i >= 0) 
    filePath = filePath.Substring(0, i) + filePath.Substring(i + TnaName.Length); 
-1

您可以使用Path類從System.IO namepace:

string filePath = "F:/jan11/MFrame/Templates/feb11"; 

Console.WriteLine(System.IO.Path.GetDirectoryName(filePath)); 
0

我不明白爲什麼正則表達式不能使用:

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 
+0

你應該使用Regex .Escape()的值。 – jcox 2017-11-09 19:06:18

+0

你的意思是,'return Regex.Replace(Regex.Replace(source),pattern,replacement);'? – toddmo 2017-11-14 18:04:42

+0

假設有人調用ReplaceEnd(「(foobar)」,「)」,thenewend) 。你的函數會拋出,因爲「)$」是一個無效的正則表達式。這將工作:返回RegexReplace(源,Regex.Escape(值)+「$」,替換);同樣的故事爲您的RemoveEnd。 – jcox 2017-11-15 15:44:31

相關問題