Check if a string (s1, can be longer as s2) begins with another string (s2), only if s1 begins with the same string data as s2, true is returned, else false. - CSharp System

CSharp examples for System:String Parse

Description

Check if a string (s1, can be longer as s2) begins with another string (s2), only if s1 begins with the same string data as s2, true is returned, else false.

Demo Code


using System.Text;
using System.Globalization;
using System.Collections.Specialized;
using System.Collections;
using System;//ww w. j  ava2  s .  co  m

public class Main{
        #endregion

        #region Comparing, Counting and Extraction
        /// <summary>
        /// Check if a string (s1, can be longer as s2) begins with another
        /// string (s2), only if s1 begins with the same string data as s2,
        /// true is returned, else false. The string compare is case insensitive.
        /// </summary>
        static public bool BeginsWith( string s1, string s2 )
        {
            return String.Compare( s1, 0, s2, 0, s2.Length, true,
                CultureInfo.CurrentCulture ) == 0;
        } // BeginsWith(s1, s2)
        /// <summary>
        /// Helps to compare strings, uses case insensitive comparison.
        /// String.Compare is also because we have always to check for == 0.
        /// This overload allows multiple strings to be checked, if any of
        /// them matches we are good to go (e.g. ("hi", {"hey", "hello", "hi"})
        /// will return true).
        /// </summary>
        static public bool Compare( string s1, string[] anyMatch )
        {
            if ( anyMatch == null )
                throw new ArgumentNullException( "anyMatch",
                    "Unable to execute method without valid anyMatch array." );

            foreach ( string match in anyMatch )
                if ( String.Compare( s1, match, true,
                    CultureInfo.CurrentCulture ) == 0 )
                    return true;
            return false;
        } // Compare(s1, anyMatch)
        /// <summary>
        /// Helps to compare strings, uses case insensitive comparison.
        /// String.Compare is also because we have always to check for == 0.
        /// </summary>
        static public bool Compare( string s1, string s2 )
        {
            return String.Compare( s1, s2, true,
                CultureInfo.CurrentCulture ) == 0;
        } // Compare(s1, s2)
}

Related Tutorials