/// <summary>
 /// 返回一个新字符串,其中当前实例中出现的所有指定字符串都替换为另一个指定的字符串。
 /// </summary>
 /// <param name="value">当前字符串。</param>
 /// <param name="oldValue">要被替换的字符串。</param>
 /// <param name="newValue">要替换出现的所有 oldValue 的字符串。</param>
 /// <param name="comparisonType">指定搜索规则的枚举值之一。</param>
 /// <returns>等效于当前字符串(除了 oldValue 的所有实例都已替换为 newValue 外)的字符串。</returns>
 /// <exception cref="System.ArgumentNullException"><c>value</c> 为 null。</exception>
 /// <exception cref="System.ArgumentNullException"><c>oldValue</c> 为 null。</exception>
 /// <exception cref="System.ArgumentException"><c>oldValue</c> 是空字符串 ("")。</exception>
 public static string Replace(this string value, string oldValue, string newValue,
     StringComparison comparisonType)
 {
     if (value == null)
     {
         throw new ArgumentNullException("value", "未将对象引用设置到对象的实例。");
     }
     if (oldValue == null)
     {
         throw new ArgumentNullException("oldValue", "值不能为 null。");
     }
     if (oldValue.Length == 0)
     {
         throw new ArgumentException("字符串的长度不能为零。", "oldValue");
     }
     if (Enum.IsDefined(typeof(StringComparison), comparisonType) == false)
     {
         throw new ArgumentException("非法的 StringComparison。", "comparisonType");
     }
     while (true)
     {
         var index = value.IndexOf(oldValue, comparisonType);
         if (index == -1)
         {
             return value;
         }
         value = value.Substring(0, index) + newValue + value.Substring(index + oldValue.Length);
     }
 }
        public static string Replace(this string source, string oldValue, string newValue, StringComparison comparisonType)
        {
            // from http://stackoverflow.com/a/22565605 with some adaptions
            if (string.IsNullOrEmpty(oldValue))
            {
                throw new ArgumentNullException("oldValue");
            }

            if (source.Length == 0)
            {
                return source;
            }

            if (newValue == null)
            {
                newValue = string.Empty;
            }

            var result = new StringBuilder();
            int startingPos = 0;
            int nextMatch;
            while ((nextMatch = source.IndexOf(oldValue, startingPos, comparisonType)) > -1)
            {
                result.Append(source, startingPos, nextMatch - startingPos);
                result.Append(newValue);
                startingPos = nextMatch + oldValue.Length;
            }

            result.Append(source, startingPos, source.Length - startingPos);

            return result.ToString();
        }
    /// <summary>
    /// Determines whether a string contans another string.
    /// </summary>
    public static bool Contains(this string source, string value, StringComparison compareMode)
    {
        if (string.IsNullOrEmpty(source))
                return false;

            return source.IndexOf(value, compareMode) >= 0;
    }
 /// <summary>
 /// Validates the specified <paramref name="value"/> and throws an <see cref="InvalidEnumArgumentException"/>
 /// exception if not valid.
 /// </summary>
 /// <param name="value">The value to validate.</param>
 /// <param name="parameterName">Name of the parameter to use if throwing exception.</param>
 public static void Validate(StringComparison value, string parameterName)
 {
     if (!IsDefined(value))
     {
         throw Error.InvalidEnumArgument(parameterName, (int)value, typeof(StringComparison));
     }
 }
 /// <summary>
 /// Validates the specified <paramref name="value"/> and throws an <see cref="InvalidEnumArgumentException"/>
 /// exception if not valid.
 /// </summary>
 /// <param name="value">The value to validate.</param>
 /// <param name="parameterName">Name of the parameter to use if throwing exception.</param>
 public static void Validate(StringComparison value, string parameterName)
 {
     if (!IsDefined(value))
     {
         throw new InvalidEnumArgumentException(parameterName, (int)value, _stringComparisonType);
     }
 }
 /// <summary>
 /// 确定此字符串是否与指定的 System.String 对象具有相同的值。 参数指定区域性、大小写以及比较所用的排序规则。
 /// </summary>
 /// <param name="this">当前 System.String 对象。</param>
 /// <param name="value">要与此实例进行比较的字符串。</param>
 /// <param name="comparisonType">枚举值之一,用于指定将如何比较字符串。</param>
 /// <returns>如果 value 参数的值为空或与此字符串相同,则为 true;否则为 false。</returns>
 public static bool EqualsSafely(this string @this, string value, StringComparison comparisonType)
 {
     if (@this == null)
     {
         return value == null;
     }
     return Enum.IsDefined(typeof(StringComparison), comparisonType) && @this.Equals(value, comparisonType);
 }
Example #7
0
 public static void PrintCompared (string a, string b, StringComparison comparison) {
     var result = String.Compare(a, b, comparison);
     if (result > 0)
         result = 1;
     else if (result < 0)
         result = -1;
     Console.WriteLine(result);
 }
 /// <summary>
 /// Determines whether the specified <paramref name="value"/> is defined by the <see cref="StringComparison"/>
 /// enumeration.
 /// </summary>
 /// <param name="value">The value to verify.</param>
 /// <returns>
 /// <c>true</c> if the specified options is defined; otherwise, <c>false</c>.
 /// </returns>
 public static bool IsDefined(StringComparison value)
 {
     return value == StringComparison.CurrentCulture ||
            value == StringComparison.CurrentCultureIgnoreCase ||
            value == StringComparison.InvariantCulture ||
            value == StringComparison.InvariantCultureIgnoreCase ||
            value == StringComparison.Ordinal ||
            value == StringComparison.OrdinalIgnoreCase;
 }
 /// <summary>
 ///     A string extension method that query if this object contains the given @this.
 /// </summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="comparisonType">Type of the comparison.</param>
 /// <param name="values">A variable-length parameters list containing values.</param>
 /// <returns>true if it contains all values, otherwise false.</returns>
 public static bool ContainsAll(this string @this, StringComparison comparisonType, params string[] values)
 {
     foreach (string value in values)
     {
         if (@this.IndexOf(value, comparisonType) == -1)
         {
             return false;
         }
     }
     return true;
 }
        /// <summary>
        /// Returns a value indicating whether the specified System.String object occurs within this string.
        /// </summary>
        /// <param name="input">The input string.</param>
        /// <param name="value">The string to seek.</param>
        /// <param name="comparisonType">One of the enumeration values that determines how this string and value are compared.</param>
        /// <returns>Returns <c>true</c> if the <paramref name="value"/> is contained within this string; otherwise <c>false</c>.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="input"/> is null</exception>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="value"/> is null</exception>
        public static bool Contains(this string input, string value, StringComparison comparisonType)
        {
            if (input == null) {
                throw new ArgumentNullException("input", "input cannot be null");
            }
            else if (value == null) {
                throw new ArgumentNullException("value", "value cannot be null");
            }

            return input.IndexOf(value, comparisonType) > -1;
        }
 /// <summary>
 /// 返回一个值,该值指示指定的 System.String 对象是否出现在此字符串中。
 /// </summary>
 /// <param name="value">当前 System.String 对象。</param>
 /// <param name="comparisonValue">要搜寻的字符串。</param>
 /// <param name="comparisonType">指定搜索规则的枚举值。</param>
 /// <returns>如果 value 参数出现在此字符串中,或者 value 为空字符串 (""),则为 true;否则为 false。</returns>
 /// <exception cref="System.ArgumentNullException"><c>value</c> 为 null。</exception>
 public static bool Contains(this string value, string comparisonValue, StringComparison comparisonType)
 {
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     if (value.Length == 0)
     {
         return true;
     }
     return value.IndexOf(comparisonValue, comparisonType) != -1;
 }
Example #12
0
    /// <summary>
    /// Look through a set of users for a user with a specific name
    /// </summary>
    /// <param name="siteUsers"></param>
    /// <param name="findName"></param>
    /// <param name="compareMode"></param>
    /// <returns> NULL = No matching user found.  Otherwise returns the user with the matching name
    /// </returns>
    public static SiteUser FindUserWithName(IEnumerable<SiteUser> siteUsers, string findName, StringComparison compareMode = StringComparison.InvariantCultureIgnoreCase)
    {
        foreach(var thisUser in siteUsers)
        {
            //If its a match return the user
            if(string.Compare(thisUser.Name, findName, compareMode) == 0)
            {
                return thisUser;
            }
        }

        return null; //no found
    }
        public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
        {
            int startIndex = 0;
            while (true)
            {
                startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
                if (startIndex == -1)
                    break;

                originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);

                startIndex += newValue.Length;
            }

            return originalString;
        }
Example #14
0
    public static string ReplaceString(this string str, string oldValue, string newValue, StringComparison comparison)
    {
        StringBuilder sb = new StringBuilder();

        int previousIndex = 0;
        int index = str.IndexOf(oldValue, comparison);
        while (index != -1)
        {
            sb.Append(str.Substring(previousIndex, index - previousIndex));
            sb.Append(newValue);
            index += oldValue.Length;

            previousIndex = index;
            index = str.IndexOf(oldValue, index, comparison);
        }
        sb.Append(str.Substring(previousIndex));

        return sb.ToString();
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestHeaderMapping"/> class.
 /// </summary>
 /// <param name="headerName">Name of the header to match.</param>
 /// <param name="headerValue">The header value to match.</param>
 /// <param name="valueComparison">The <see cref="StringComparison"/> to use when matching <paramref name="headerValue"/>.</param>
 /// <param name="isValueSubstring">if set to <c>true</c> then <paramref name="headerValue"/> is 
 /// considered a match if it matches a substring of the actual header value.</param>
 /// <param name="mediaType">The <see cref="MediaTypeHeaderValue"/> to use if <paramref name="headerName"/> and <paramref name="headerValue"/> 
 /// is considered a match.</param>
 public RequestHeaderMapping(string headerName, string headerValue, StringComparison valueComparison, bool isValueSubstring, MediaTypeHeaderValue mediaType)
     : base(mediaType)
 {
     Initialize(headerName, headerValue, valueComparison, isValueSubstring);
 }
Example #16
0
 /// <summary>
 /// Constructs a new RowConfigReader which reads from the given string.
 /// <param name="buffer">The string to parse through.</param>
 /// <param name="comparisonKind">The comparison kind to use.</param>
 /// </summary>
 public RowConfigReader(string buffer, StringComparison comparisonKind)
 {
     _buffer = buffer;
     _comparisonKind = comparisonKind;
     _currentIndex = 0;
 }
Example #17
0
 public static bool Equals(this ReadOnlySpan <Char8> utf8Text, ReadOnlySpan <Char8> value, StringComparison stringComparison) => throw null;
Example #18
0
 public static void Contains(string s, string value, StringComparison comparisonType, bool expected)
 {
     Assert.Equal(expected, s.Contains(value, comparisonType));
 }
Example #19
0
 public static bool Contains(this IEnumerable <string> source, string toCheck, StringComparison comp)
 {
     if (source == null)
     {
         return(false);
     }
     return(source.Where(s => s.Contains(toCheck, comp)).Any());
 }
Example #20
0
 public static bool Contains(this string haystack, string needle, StringComparison stringComparison)
 {
     return(haystack.IndexOf(needle, stringComparison) != -1);
 }
        /// <summary>
        /// Asserts that a redirect to a certain location took place.
        /// </summary>
        /// <param name="response">The <see cref="BrowserResponse"/> that the assert should be made on.</param>
        /// <param name="location">The location that should have been redirected to.</param>
        /// <param name="stringComparer">The string comparer that should be used by the assertion. The default value is <see cref="StringComparison.Ordinal"/>.</param>
        public static void ShouldHaveRedirectedTo(this BrowserResponse response, string location, StringComparison stringComparer = StringComparison.Ordinal)
        {
            var validRedirectStatuses = new[]
            {
                HttpStatusCode.MovedPermanently,
                HttpStatusCode.SeeOther,
                HttpStatusCode.TemporaryRedirect
            };

            if (!validRedirectStatuses.Any(x => x == response.StatusCode))
            {
                throw new AssertException(
                          String.Format("Status code should be one of 'MovedPermanently, SeeOther, TemporaryRedirect', but was {0}.", response.StatusCode));
            }

            if (!response.Headers["Location"].Equals(location, stringComparer))
            {
                throw new AssertException(String.Format("Location should have been: {0}, but was {1}", location, response.Headers["Location"]));
            }
        }
Example #22
0
 public static void GetHashCode_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType)
 {
     AssertExtensions.Throws <ArgumentException>("comparisonType", () => "abc".GetHashCode(comparisonType));
 }
 public static string Replace(this string target, string oldValue, string?newValue, StringComparison _)
 {
     return(target.Replace(oldValue, newValue));
 }
Example #24
0
 public void Replace_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType)
 {
     AssertExtensions.Throws <ArgumentException>("comparisonType", () => "abc".Replace("abc", "def", comparisonType));
 }
Example #25
0
 public static void GetHashCode_StringComparison(StringComparison comparisonType)
 {
     Assert.Equal(StringComparer.FromComparison(comparisonType).GetHashCode("abc"), "abc".GetHashCode(comparisonType));
 }
Example #26
0
 public void Replace_StringComparison_ReturnsExpected(string original, string oldValue, string newValue, StringComparison comparisonType, string expected)
 {
     Assert.Equal(expected, original.Replace(oldValue, newValue, comparisonType));
 }
Example #27
0
 public static void Contains_InvalidComparisonType_ThrowsArgumentOutOfRangeException(StringComparison comparisonType)
 {
     AssertExtensions.Throws <ArgumentException>("comparisonType", () => "ab".Contains("a", comparisonType));
 }
Example #28
0
 public static void Contains_NullValue_ThrowsArgumentNullException(StringComparison comparisonType)
 {
     AssertExtensions.Throws <ArgumentNullException>("value", () => "foo".Contains(null, comparisonType));
 }
 public static bool Contains(this string target, char value, StringComparison _)
 {
     return(target.Contains(value));
 }
Example #30
0
 // This API is useful, but perhaps best suited as a normal static method on a helper type rather than as an extension method?
 public static int GetHashCode(this ReadOnlySpan <Char8> utf8Text, StringComparison comparisonType) => throw null;
Example #31
0
 public static bool StartsWith(this ReadOnlySpan <Char8> utf8Text, ReadOnlySpan <Char8> value, StringComparison comparisonType) => throw null;
Example #32
0
 public static int IndexOf(this ReadOnlySpan <Char8> utf8Text, ReadOnlySpan <Char8> value, StringComparison stringComparison) => throw null;
Example #33
0
 public static bool Contains(this string source, string value, StringComparison comparrisonType)         //Faster than String.ToLower().Contains(String.ToLower());
 {
     return(source != null && value != null && source.IndexOf(value, comparrisonType) >= 0);
 }
Example #34
0
 public static int CompareTo(this ReadOnlySpan <Char8> utf8Text, ReadOnlySpan <Char8> other, StringComparison comparisonType) => throw null;
Example #35
0
    [InlineData("123", 123, StringComparison.OrdinalIgnoreCase, false)] // Not a string
    public static void TestEquals(string s1, object obj, StringComparison comparisonType, bool expected)
    {
        string s2 = obj as string;
        if (s1 != null)
        {
            if (comparisonType == StringComparison.Ordinal)
            {
                // Use Equals(object)
                Assert.Equal(expected, s1.Equals(obj));
                Assert.Equal(expected, s1.Equals(s2));
            }
            // Use Equals(string, comparisonType)
            Assert.Equal(expected, s1.Equals(s2, comparisonType));
        }
        if (comparisonType == StringComparison.Ordinal)
        {
            // Use Equals(string, string)
            Assert.Equal(expected, string.Equals(s1, s2));
        }
        // Use Equals(string, string, StringComparisonType)
        Assert.Equal(expected, string.Equals(s1, s2, comparisonType));

        // If two strings are equal ordinally, then they must have the same hash code.
        if (s1 != null && s2 != null && comparisonType == StringComparison.Ordinal)
        {
            Assert.Equal(expected, s1.GetHashCode().Equals(s2.GetHashCode()));
        }
        if (s1 != null)
        {
            Assert.Equal(s1.GetHashCode(), s1.GetHashCode());
        }
    }
Example #36
0
 public static int IndexOfAny(this ReadOnlySpan <Char8> utf8Text, ReadOnlySpan <UnicodeScalar> values, StringComparison stringComparison) => throw null;
Example #37
0
 public static bool Contains(this string haystack, string needle, StringComparison stringComparison)
 => haystack.IndexOf(needle, stringComparison) >= 0;
Example #38
0
 public static void Contains(this ReadOnlySpan <Char8> utf8Text, UnicodeScalar value, StringComparison comparisonType) => throw null;
Example #39
0
 public static void TestCompareIndexed(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType, int expected)
 {
     if (comparisonType == StringComparison.CurrentCulture)
     {
         Assert.Equal(expected, NormalizeCompare(String.Compare(strA, indexA, strB, indexB, length)));
     }
     else if (comparisonType == StringComparison.Ordinal)
     {
         Assert.Equal(expected, NormalizeCompare(String.CompareOrdinal(strA, indexA, strB, indexB, length)));
     }
     Assert.Equal(expected, NormalizeCompare(String.Compare(strA, indexA, strB, indexB, length, comparisonType)));
 }
Example #40
0
    public static IEnumerable<object[]> AllSubstringsAndComparisons(string source)
    {
        var comparisons = new StringComparison[] {
            StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase,
            StringComparison.Ordinal, StringComparison.OrdinalIgnoreCase
        };

        foreach (StringComparison comparison in comparisons)
            for (int i = 0; i <= source.Length; i++)
                for (int subLen = source.Length - i; subLen > 0; subLen--)
                    yield return new object[] { source, source.Substring(i, subLen), i, comparison };
    }
Example #41
0
 public static void TestEquals_InvalidComparisonType_ThrowsArgumentOutOfRangeException(StringComparison comparisonType)
 {
     // Invalid comparison type
     Assert.Throws<ArgumentException>("comparisonType", () => string.Equals("a", "b", comparisonType));
     Assert.Throws<ArgumentException>("comparisonType", () => "a".Equals("a", comparisonType));
 }
Example #42
0
 public static void TestEndsWith_NullInStrings(StringComparison comparison)
 {
     Assert.True("\0test".EndsWith("test", comparison));
     Assert.True("te\0st".EndsWith("e\0st", comparison));
     Assert.False("te\0st".EndsWith("test", comparison));
     Assert.False("test\0".EndsWith("test", comparison));
     Assert.False("test".EndsWith("\0st", comparison));
 }
Example #43
0
        private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType)
        {
            if (string.IsNullOrEmpty(relativeTo)) throw new ArgumentNullException(nameof(relativeTo));
            if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException(nameof(path));
            Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase);

            relativeTo = GetFullPath(relativeTo);
            path = GetFullPath(path);

            // Need to check if the roots are different- if they are we need to return the "to" path.
            if (!PathInternal.AreRootsEqual(relativeTo, path, comparisonType))
                return path;

            int commonLength = PathInternal.GetCommonPathLength(relativeTo, path, ignoreCase: comparisonType == StringComparison.OrdinalIgnoreCase);

            // If there is nothing in common they can't share the same root, return the "to" path as is.
            if (commonLength == 0)
                return path;

            // Trailing separators aren't significant for comparison
            int relativeToLength = relativeTo.Length;
            if (PathInternal.EndsInDirectorySeparator(relativeTo))
                relativeToLength--;

            bool pathEndsInSeparator = PathInternal.EndsInDirectorySeparator(path);
            int pathLength = path.Length;
            if (pathEndsInSeparator)
                pathLength--;

            // If we have effectively the same path, return "."
            if (relativeToLength == pathLength && commonLength >= relativeToLength) return ".";

            // We have the same root, we need to calculate the difference now using the
            // common Length and Segment count past the length.
            //
            // Some examples:
            //
            //  C:\Foo C:\Bar L3, S1 -> ..\Bar
            //  C:\Foo C:\Foo\Bar L6, S0 -> Bar
            //  C:\Foo\Bar C:\Bar\Bar L3, S2 -> ..\..\Bar\Bar
            //  C:\Foo\Foo C:\Foo\Bar L7, S1 -> ..\Bar

            StringBuilder sb = StringBuilderCache.Acquire(Math.Max(relativeTo.Length, path.Length));

            // Add parent segments for segments past the common on the "from" path
            if (commonLength < relativeToLength)
            {
                sb.Append(PathInternal.ParentDirectoryPrefix);

                for (int i = commonLength; i < relativeToLength; i++)
                {
                    if (PathInternal.IsDirectorySeparator(relativeTo[i]))
                    {
                        sb.Append(PathInternal.ParentDirectoryPrefix);
                    }
                }
            }
            else if (PathInternal.IsDirectorySeparator(path[commonLength]))
            {
                // No parent segments and we need to eat the initial separator
                //  (C:\Foo C:\Foo\Bar case)
                commonLength++;
            }

            // Now add the rest of the "to" path, adding back the trailing separator
            int count = pathLength - commonLength;
            if (pathEndsInSeparator)
                count++;

            sb.Append(path, commonLength, count);
            return StringBuilderCache.GetStringAndRelease(sb);
        }
        internal static bool IsNameAlreadyAMemberName(StructuralType type, string generatedPropertyName, StringComparison comparison)
        {
            foreach (EdmMember member in type.Members)
            {
                if (member.DeclaringType == type &&
                    member.Name.Equals(generatedPropertyName, comparison))
                {
                    return true;
                }
            }

            return false;
        }
 public static bool Contains(this string str, string value, StringComparison comparisonType)
     => str.IndexOf(value, comparisonType) >= 0;
 /// <summary>
 /// Returns true if a specified substring occurs within this string, false otherwise.
 /// </summary>
 /// <param name="input">The main string value </param>
 /// <param name="substring">The substring to check</param>
 /// <param name="comp">The comparison rule</param>
 /// <returns>True or false</returns>
 public static bool Contains(this string input, string substring, StringComparison comp) => input?.IndexOf(substring, comp) > 0;
Example #47
0
    public static void TestLastIndexOf_AllSubstrings(string source, string substring, int i, StringComparison comparison)
    {
        bool ignoringCase =
            comparison == StringComparison.OrdinalIgnoreCase ||
            comparison == StringComparison.CurrentCultureIgnoreCase;

        // First find the substring.  We should be able to with all comparison types.
        Assert.Equal(i, source.LastIndexOf(substring, comparison)); // in the whole string
        Assert.Equal(i, source.LastIndexOf(substring, i + substring.Length - 1, comparison)); // starting at end of substring
        Assert.Equal(i, source.LastIndexOf(substring, i + substring.Length, comparison)); // starting just beyond end of substring
        if (i + substring.Length < source.Length)
        {
            Assert.Equal(i, source.LastIndexOf(substring, i + substring.Length + 1, comparison)); // starting a bit more beyond end of substring
        }
        if (i + substring.Length > 1)
        {
            Assert.Equal(-1, source.LastIndexOf(substring, i + substring.Length - 2, comparison)); // starting before end of substring
        }

        // Shouldn't be able to find the substring if the count is less than substring's length
        Assert.Equal(-1, source.LastIndexOf(substring, source.Length - 1, substring.Length - 1, comparison));

        // Now double the source.  Make sure we find the second copy of the substring.
        int halfLen = source.Length;
        source += source;
        Assert.Equal(halfLen + i, source.LastIndexOf(substring, comparison));

        // Now change the case of a letter.
        source = source.ToUpperInvariant();
        Assert.Equal(
            ignoringCase ? halfLen + i : -1,
            source.LastIndexOf(substring, comparison));
    }
Example #48
0
 public StringComparison GetEnum(StringComparison value = StringComparison.InvariantCulture) => value;
Example #49
0
 public static void TestEndsWith(StringComparison comparisonType, string text, string value, bool expected)
 {
     if (comparisonType == StringComparison.CurrentCulture)
     {
         Assert.Equal(expected, text.EndsWith(value));
     }
     Assert.Equal(expected, text.EndsWith(value, comparisonType));
 }
Example #50
0
 public StringComparison GetEnum([Optional] StringComparison value) => value;
Example #51
0
    public static void TestIndexOf_AllSubstrings(string source, string substring, int i, StringComparison comparison)
    {
        bool ignoringCase =
            comparison == StringComparison.OrdinalIgnoreCase ||
            comparison == StringComparison.CurrentCultureIgnoreCase;

        // First find the substring.  We should be able to with all comparison types.
        Assert.Equal(i, source.IndexOf(substring, comparison)); // in the whole string
        Assert.Equal(i, source.IndexOf(substring, i, comparison)); // starting at substring
        if (i > 0)
        {
            Assert.Equal(i, source.IndexOf(substring, i - 1, comparison)); // starting just before substring
        }
        Assert.Equal(-1, source.IndexOf(substring, i + 1, comparison)); // starting just after start of substring

        // Shouldn't be able to find the substring if the count is less than substring's length
        Assert.Equal(-1, source.IndexOf(substring, 0, substring.Length - 1, comparison));

        // Now double the source.  Make sure we find the first copy of the substring.
        int halfLen = source.Length;
        source += source;
        Assert.Equal(i, source.IndexOf(substring, comparison));

        // Now change the case of a letter.
        source = source.ToUpperInvariant();
        Assert.Equal(
            ignoringCase ? i : -1,
            source.IndexOf(substring, comparison));
    }
Example #52
0
 public static bool Contains(this string source, string toCheck, StringComparison comp)
 {
     return(source?.IndexOf(toCheck, comp) >= 0);
 }
Example #53
0
 /// <summary>
 /// Constructs a new RowConfigReader which reads from the given string.
 /// <param name="buffer">The string to parse through.</param>
 /// </summary>
 public RowConfigReader(string buffer)
 {
     _buffer = buffer;
     _comparisonKind = StringComparison.Ordinal;
     _currentIndex = 0;
 }
Example #54
0
        public bool FindNext(ITextEditorAdaptor <T> editor, int minPos, int maxPos)
        {
            if (String.IsNullOrEmpty(this.FindText))
            {
                this.ShowMessage("No Find Text specified");
                return(false);
            }
            String find = this.FindText;

            //Validate Regex
            if (this.UseRegex)
            {
                try
                {
                    Regex.IsMatch(String.Empty, find);
                }
                catch (Exception ex)
                {
                    this.ShowMessage("Regular Expression is malformed - " + ex.Message);
                    return(false);
                }
            }

            //Add Search Text to Combo Box for later reuse
            if (!this.RecentFindTexts.Contains(find))
            {
                this.RecentFindTexts.Add(find);
            }

            int start = editor.CaretOffset;
            int pos;
            int length = find.Length;
            StringComparison compareMode = this.MatchCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
            RegexOptions     regexOps    = this.MatchCase ? RegexOptions.None : RegexOptions.IgnoreCase;

            if (this.SearchUp)
            {
                //Search portion of Document prior to current position
                if (this.UseRegex)
                {
                    MatchCollection ms = Regex.Matches(editor.Text.Substring(0, start), find, regexOps);
                    if (ms.Count == 0)
                    {
                        pos = -1;
                    }
                    else
                    {
                        pos    = ms[ms.Count - 1].Index;
                        length = ms[ms.Count - 1].Length;
                    }
                }
                else
                {
                    pos = editor.Text.Substring(0, start).LastIndexOf(find, compareMode);
                }
            }
            else
            {
                //Search position of Document subsequent to current position (incl. any selected text)
                start += editor.SelectionLength;
                if (this.UseRegex)
                {
                    Match m = Regex.Match(editor.Text.Substring(start), find, regexOps);
                    if (!m.Success)
                    {
                        pos = -1;
                    }
                    else
                    {
                        pos    = start + m.Index;
                        length = m.Length;
                    }
                }
                else
                {
                    pos = editor.Text.IndexOf(find, start, compareMode);
                }
            }

            //If we've found the position of the next highlight it and return true otherwise return false
            if (pos > -1)
            {
                //Check we meet any document range restrictions
                if (pos < minPos || pos > maxPos)
                {
                    editor.CaretOffset     = pos;
                    editor.SelectionStart  = pos;
                    editor.SelectionLength = length;
                    return(this.FindNext(editor, minPos, maxPos));
                }

                //If Matching on whole word ensure that their are boundaries before and after the match
                if (this.MatchWholeWord)
                {
                    //Check boundary before
                    if (pos > 0)
                    {
                        char c = editor.Text[pos - 1];
                        if (Char.IsLetterOrDigit(c))
                        {
                            //Not a boundary so adjust start position and recurse
                            editor.CaretOffset = pos + length;
                            if (!this.SearchUp)
                            {
                                editor.CaretOffset -= editor.SelectionLength;
                            }
                            return(this.FindNext(editor));
                        }
                    }
                    //Check boundary after
                    if (pos + length < editor.Text.Length - 1)
                    {
                        char c = editor.Text[pos + length];
                        if (Char.IsLetterOrDigit(c))
                        {
                            //Not a boundary so adjust start position and recurse
                            editor.CaretOffset = pos + length - 1;
                            if (!this.SearchUp)
                            {
                                editor.CaretOffset -= editor.SelectionLength;
                            }
                            return(this.FindNext(editor));
                        }
                    }
                }

                editor.Select(pos, length);
                editor.CaretOffset = pos;
                editor.ScrollToLine(editor.GetLineByOffset(pos));
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #55
0
 /// <summary>
 ///     A string extension method that query if this object contains the given value.
 /// </summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="value">The value.</param>
 /// <param name="comparisonType">Type of the comparison.</param>
 /// <returns>true if the value is in the string, false if not.</returns>
 /// <example>
 ///     <code>
 ///           using System;
 ///           using Microsoft.VisualStudio.TestTools.UnitTesting;
 ///           using Z.ExtensionMethods;
 ///           
 ///           namespace ExtensionMethods.Examples
 ///           {
 ///               [TestClass]
 ///               public class System_String_Contains
 ///               {
 ///                   [TestMethod]
 ///                   public void Contains()
 ///                   {
 ///                       // Type
 ///                       string @this = &quot;Fizz&quot;;
 ///           
 ///                       // Examples
 ///                       bool value1 = @this.Contains(&quot;f&quot;, StringComparison.InvariantCultureIgnoreCase); // return true;
 ///                       bool value2 = @this.Contains(&quot;f&quot;, StringComparison.InvariantCulture); // return false;
 ///                       bool value3 = @this.Contains(&quot;F&quot;); // return true;
 ///           
 ///                       // Unit Test
 ///                       Assert.IsTrue(value1);
 ///                       Assert.IsFalse(value2);
 ///                       Assert.IsTrue(value3);
 ///                   }
 ///               }
 ///           }
 ///     </code>
 /// </example>
 public static bool Contains(this string @this, string value, StringComparison comparisonType)
 {
     return @this.IndexOf(value, comparisonType) != -1;
 }
Example #56
0
 public static TextTaggerBase GetStartWithTagger(IClassificationTag tag, string prefix, bool skipLeadingWhitespace, StringComparison comparison)
 {
     return(new StartWithTagger {
         Prefix = prefix, StringComparison = comparison, Tag = tag, SkipLeadingWhitespace = skipLeadingWhitespace
     });
 }
        private void Initialize(string headerName, string headerValue, StringComparison valueComparison, bool isValueSubstring)
        {
            if (String.IsNullOrWhiteSpace(headerName))
            {
                throw Error.ArgumentNull("headerName");
            }

            if (String.IsNullOrWhiteSpace(headerValue))
            {
                throw Error.ArgumentNull("headerValue");
            }

            StringComparisonHelper.Validate(valueComparison, "valueComparison");

            HeaderName = headerName;
            HeaderValue = headerValue;
            HeaderValueComparison = valueComparison;
            IsValueSubstring = isValueSubstring;
        }
Example #58
0
 public static TextTaggerBase GetRegexTagger(IClassificationTag tag, string pattern, int useGroup, StringComparison comparison)
 {
     return(new RegexTagger {
         Pattern = pattern, StringComparison = comparison, UseGroup = useGroup, Tag = tag
     });
 }
        private static double MatchHeaderValue(HttpRequestMessage request, string headerName, string headerValue, StringComparison valueComparison, bool isValueSubstring)
        {
            Contract.Assert(request != null, "request should not be null");
            Contract.Assert(headerName != null, "header name should not be null");
            Contract.Assert(headerValue != null, "header value should not be null");

            IEnumerable<string> values;
            if (request.Headers.TryGetValues(headerName, out values))
            {
                foreach (string value in values)
                {
                    if (isValueSubstring)
                    {
                        if (value.IndexOf(headerValue, valueComparison) != -1)
                        {
                            return FormattingUtilities.Match;
                        }
                    }
                    else
                    {
                        if (value.Equals(headerValue, valueComparison))
                        {
                            return FormattingUtilities.Match;
                        }
                    }
                }
            }

            return FormattingUtilities.NoMatch;
        }
Example #60
0
 public void ReplaceWithStringComparerTest(string aString, string oldValue, string newValue, StringComparison stringComparison, string expectedReplace)
 {
     aString.Replace(oldValue, newValue, stringComparison).ShouldBe(expectedReplace);
 }