Get index of a string from a given index in StringBuilder - CSharp Language Basics

CSharp examples for Language Basics:StringBuilder

Description

Get index of a string from a given index in StringBuilder

Demo Code


using System.Text;
using System;/*from  w  w  w.  j  ava  2s.c  o  m*/

public class Main{
        /// <summary>
        /// Get index of a string from a given index
        /// </summary>
        /// <param name="sb">StringBuilder object</param>
        /// <param name="value">String to search for</param>
        /// <param name="startIndex">Index to begin at</param>
        /// <returns>Returns the index of the given string, -1 if not found</returns>
        public static int IndexOf(this StringBuilder sb, string value, int startIndex)
        {
            Validation.IsNotNull(sb, "sb");
            Validation.IsNotNullOrEmpty(value, "value");
            Validation.Validate<ArgumentOutOfRangeException>(startIndex >= 0 && startIndex < int.MaxValue);
            Validation.Validate(startIndex < sb.Length);

            return sb.ToString().IndexOf(value, startIndex, StringComparison.InvariantCulture);
        }
        /// <summary>
        /// Get index of a string
        /// </summary>
        /// <param name="sb">StringBuilder object</param>
        /// <param name="value">String to search for</param>
        /// <returns>Returns the index of the string, -1 if not found</returns>
        public static int IndexOf(this StringBuilder sb, string value)
        {
            Validation.IsNotNull(sb, "sb");
            Validation.IsNotNullOrEmpty(value, "value");

            return sb.ToString().IndexOf(value, StringComparison.InvariantCulture);
        }
        /// <summary>
        /// Get index of a char starting from a given index
        /// </summary>
        /// <param name="sb">StringBuilder object</param>
        /// <param name="value">Character to search for</param>
        /// <param name="startIndex">Index to begin at</param>
        /// <returns>Returns the index of the given character, -1 if not found</returns>
        public static int IndexOf(this StringBuilder sb, char value, int startIndex)
        {
            Validation.IsNotNull(sb, "sb");
            Validation.Validate<ArgumentOutOfRangeException>(startIndex >= 0 && startIndex < int.MaxValue);
            Validation.Validate(startIndex < sb.Length);

            return sb.ToString().IndexOf(value, startIndex);
        }
        /// <summary>
        /// Get index of a char
        /// </summary>
        /// <param name="sb">StringBuilder object</param>
        /// <param name="value">Character to search for</param>
        /// <returns>Returns the index of the indicated character, -1 if not found</returns>
        public static int IndexOf(this StringBuilder sb, char value)
        {
            Validation.IsNotNull(sb, "sb");
            Validation.Validate(sb.Length > 0);

            return IndexOf(sb, value, 0);
        }
}

Related Tutorials