예제 #1
0
        /// <summary>
        /// Helper method to count how many times the given string appears in this string.
        /// </summary>
        /// <param name="str">This <see cref="String"/>.</param>
        /// <param name="substring">The string to search. May be <c>null</c>, in which case result is <c>0</c>.</param>
        /// <param name="comparison">The <see cref="StringComparison"/> to use.</param>
        /// <returns>The amount of times <paramref name="substring"/> appears in this <see cref="String"/>.</returns>
        /// <exception cref="NullReferenceException">If this <see cref="String"/> is <c>null</c>.</exception>
        public static Int32 CountOccurrances(this String str, String substring, StringComparison comparison)
        {
            ArgumentValidator.ValidateNotNullReference(str);

            var count = 0;

            if (!String.IsNullOrEmpty(substring))
            {
                var idx = 0;
                while ((idx = str.IndexOf(substring, idx, comparison)) != -1)
                {
                    idx += substring.Length;
                    ++count;
                }
            }

            return(count);
        }
예제 #2
0
        /// <summary>
        /// Creates the default encoding information for given <see cref="Encoding"/>.
        /// </summary>
        /// <param name="encoding">This <see cref="Encoding"/>.</param>
        /// <returns>A new instance of <see cref="IEncodingInfo"/>.</returns>
        /// <exception cref="InvalidOperationException">If this method could not automatically deduct which <see cref="IEncodingInfo"/> to create.</exception>
        public static IEncodingInfo CreateDefaultEncodingInfo(this Encoding encoding)
        {
            ArgumentValidator.ValidateNotNullReference(encoding);

            switch (encoding)
            {
#if !NETSTANDARD1_0 && !NETSTANDARD1_1
            case ASCIIEncoding ascii:
                return(ASCIIEncodingInfo.Instance);
#endif
            case UTF8Encoding utf8:
                return(new UTF8EncodingInfo(utf8));

            case UnicodeEncoding utf16:
                if (ReferenceEquals(utf16, Encoding.Unicode))
                {
                    return(new UTF16LEEncodingInfo(utf16));
                }
                else if (ReferenceEquals(utf16, Encoding.BigEndianUnicode) || UTF16EncodingInfo.IsBigEndian(utf16))
                {
                    return(new UTF16BEEncodingInfo(utf16));
                }
                else
                {
                    return(new UTF16LEEncodingInfo(utf16));
                }

#if NET_40 || NETSTANDARD1_5 || NET_45
            case UTF32Encoding utf32:
                return(new UTF32EncodingInfo(utf32));
#endif
            case null:
                return(null);

            default:
                throw new InvalidOperationException($"Could not create default encoding info for {encoding}.");
            }
        }