Returns the part of the string before the last occurrence of the given string, or null when the original text does not contain the text to find. - CSharp System

CSharp examples for System:String Contain

Description

Returns the part of the string before the last occurrence of the given string, or null when the original text does not contain the text to find.

Demo Code


using System;//from w  w  w  .j  a  va2  s  .  c  o  m

public class Main{
        /// <summary>
        /// Returns the part of the string before the last occurrence of the given string,
        /// or null when the original text does not contain the text to find. 
        /// </summary>
        public static string BeforeLast(this string originalText, string textToFind)
        {
            if (String.IsNullOrEmpty(originalText) || !originalText.Contains(textToFind))
            {
                return null;
            }

            return originalText.Substring(0, originalText.LastIndexOf(textToFind, StringComparison.Ordinal));
        }
}

Related Tutorials