99

文字列内の最後の単語を置き換える必要があるという問題があります。

状況:次の形式の文字列が与えられました。

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

次に、次のように置き換えTnaNameます。

filePath = filePath.Replace(TnaName, ""); // feb11 is TnaName

これは機能しますが、 が私TnaNameの と同じ場合に問題がありfolder nameます。これが発生すると、次のような文字列が得られます。

F:/feb11/MFrame/Templates/feb11

これで、両方の出現箇所が に置き換えられましTnaNamefeb11。文字列の最後の単語のみを置き換える方法はありますか?

注:これfeb11TnaName別のプロセスからのものです-それは問題ではありません。

4

8 に答える 8

12

を使用string.LastIndexOf()して文字列が最後に出現するインデックスを見つけ、substring を使用して解決策を探します。

于 2013-02-12T05:28:57.530 に答える
8

手動で置換を行う必要があります。

int i = filePath.LastIndexOf(TnaName);
if (i >= 0)
    filePath = filePath.Substring(0, i) + filePath.Substring(i + TnaName.Length);
于 2013-02-12T05:33:59.037 に答える
4

正規表現を使用できない理由がわかりません:

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
于 2016-08-25T21:28:22.133 に答える
0

名前空間Pathからクラスを使用できます。System.IO

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

Console.WriteLine(System.IO.Path.GetDirectoryName(filePath));
于 2013-02-12T05:37:42.517 に答える