Returns the index of the first character that satisfies the given predicate. - CSharp System

CSharp examples for System:Char

Description

Returns the index of the first character that satisfies the given predicate.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System;//from  w w  w . ja  v  a 2  s  .c  o m

public class Main{
        /// <summary>
		/// Returns the index of the first character that satisfies the given predicate.
		/// </summary>
		/// <param name="s">The string to search.</param>
		/// <param name="startIndex">The index to start search at</param>
		/// <param name="acceptChar">
		/// The predicate that every character is asserted against.
		/// </param>
		/// <returns>
		/// The index of the first character that satisfies <c>predicate</c> or -1 if no
		/// characters satisfy <c>predicate</c>.
		/// </returns>
		public static int IndexOf(this string s, int startIndex, Predicate<char> acceptChar)
		{
			for (var i = startIndex; i < s.Length; i++)
			{
				if (acceptChar(s[i]))
				{
					return i;
				}
			}

			return -1;
		}
        /// <summary>
		/// Returns the index of the first character that satifies the predicate.
		/// </summary>
		/// <param name="s">The string to search</param>
		/// <param name="acceptChar">The predicate</param>
		/// <returns>The index of the first character if found otherwise -1</returns>
		public static int IndexOf(this string s, Predicate<char> acceptChar)
		{
			return s.IndexOf(0, acceptChar);
		}
}

Related Tutorials