programing

문자열의 마지막 단어 바꾸기 - C#

sourcejob 2023. 5. 9. 22:38
반응형

문자열의 마지막 단어 바꾸기 - 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그것은 다른 과정에서 발생합니다 - 그건 문제가 아닙니다.

다음은 마지막 발생을 대체하는 기능입니다.string

public static string ReplaceLastOccurrence(string source, string find, string replace)
{
    int place = source.LastIndexOf(find);
    
    if (place == -1)
       return source;
    
    return source.Remove(place, find.Length).Insert(place, replace);
}
  • source작업을 수행할 문자열입니다.
  • find바꿀 문자열입니다.
  • replace대체할 문자열입니다.

사용하다string.LastIndexOf()마지막 문자열의 인덱스를 찾은 다음 하위 문자열을 사용하여 솔루션을 찾습니다.

교체는 수동으로 수행해야 합니다.

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

Regex를 사용할 수 없는 이유를 모르겠습니다.

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

솔루션은 한 줄로 훨씬 더 간단하게 구현할 수 있습니다.

 static string ReplaceLastOccurrence(string str, string toReplace, string replacement)
    {
        return Regex.Replace(str, $@"^(.*){Regex.Escape(toReplace)}(.*?)$", $"$1{Regex.Escape(replacement)}$2");
    }

따라서 정규식 별표 연산자의 탐욕을 이용합니다.이 기능은 다음과 같이 사용됩니다.

var s = "F:/feb11/MFrame/Templates/feb11";
var tnaName = "feb11";
var r = ReplaceLastOccurrence(s,tnaName, string.Empty);

를 사용할 수 있습니다.Path로부터의 수업.System.IO네임스페이스:

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

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

다음 함수는 패턴(교체할 단어)이 마지막으로 발생하는 문자열을 분할합니다.
그런 다음 대체 문자열(문자열의 두 번째 절반)을 사용하여 패턴을 변경합니다.
마지막으로, 두 문자열 반을 다시 서로 연결합니다.

using System.Text.RegularExpressions;

public string ReplaceLastOccurance(string source, string pattern, string replacement)
{
   int splitStartIndex = source.LastIndexOf(pattern, StringComparison.OrdinalIgnoreCase);
   string firstHalf = source.Substring(0, splitStartIndex);
   string secondHalf = source.Substring(splitStartIndex, source.Length - splitStartIndex);
   secondHalf = Regex.Replace(secondHalf, pattern, replacement, RegexOptions.IgnoreCase);

   return firstHalf + secondHalf;
}

언급URL : https://stackoverflow.com/questions/14825949/replace-the-last-occurrence-of-a-word-in-a-string-c-sharp

반응형