Gets a string that starts with and ends with a selected string. The end result starts from a index start index. - CSharp System

CSharp examples for System:String Start End

Description

Gets a string that starts with and ends with a selected string. The end result starts from a index start index.

Demo Code

//     TelerikAcademy.com. All rights reserved.
using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System;/*from w w w  .j  a  va2 s. c om*/

public class Main{
        /// <summary>
        /// Gets a string that starts with and ends with a selected string. The end result starts from a index start index.
        /// </summary>
        /// <param name="input">Input string.</param>
        /// <param name="startString">Start string input.</param>
        /// <param name="endString">End string input.</param>
        /// <param name="startFrom">Starts from index. If no start index is selected the default index equals 0.</param>
        /// <returns>Return the converted string from the given start until its end.</returns>
        public static string GetStringBetween(this string input, string startString, string endString, int startFrom = 0)
        {
            input = input.Substring(startFrom);
            startFrom = 0;
            if (!input.Contains(startString) || !input.Contains(endString))
            {
                return string.Empty;
            }

            var startPosition = input.IndexOf(startString, startFrom, StringComparison.Ordinal) + startString.Length;
            if (startPosition == -1)
            {
                return string.Empty;
            }

            var endPosition = input.IndexOf(endString, startPosition, StringComparison.Ordinal);
            if (endPosition == -1)
            {
                return string.Empty;
            }

            return input.Substring(startPosition, endPosition - startPosition);
        }
}

Related Tutorials