C# – Replace Last Occurrence of a String

The below code example shows you the way to replace the last occurrence of a string in C# (C Sharp).

using System;

namespace ByteNota
    class StringExample
        static string ReplaceLast(string find, string replace, string str)
            int lastIndex = str.LastIndexOf(find);

            if (lastIndex == -1)
                return str;

            string beginString = str.Substring(0, lastIndex);
            string endString = str.Substring(lastIndex + find.Length);

            return beginString + replace + endString;

        static void Main(string[] args)
            String str1 = "Hello World-";
            String newStr1 = ReplaceLast("-", "", str1);
            Console.WriteLine(newStr1); // Hello World

            String str2 = "Foo and Bar. Hello Bar";
            String newStr2 = ReplaceLast("Bar", "guys", str2);
            Console.WriteLine(newStr2); // Foo and Bar. Hello guys



Hello World
Foo and Bar. Hello guys

Leave a Reply