fCraft.Color.IsValidColorCode C# (CSharp) Method

IsValidColorCode() public static method

Checks whether a color code is valid (checks if it's hexadecimal char).
public static IsValidColorCode ( char code ) : bool
code char
return bool
        public static bool IsValidColorCode( char code ) {
            return ( code >= '0' && code <= '9' ) || ( code >= 'a' && code <= 'f' ) || ( code >= 'A' && code <= 'F' );
        }

Usage Example

Example #1
0
        public static string ReplacePercentColorCodes([NotNull] string message, bool allowNewlines)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            int startIndex = message.IndexOf('%');

            if (startIndex == -1)
            {
                return(message); // break out early if there are no percent marks
            }

            StringBuilder output            = new StringBuilder(message.Length);
            int           lastAppendedIndex = 0;

            while (startIndex != -1 && startIndex < message.Length - 1)
            {
                // see if colorcode was escaped (if odd number of backslashes precede it)
                bool escaped = false;
                for (int i = startIndex - 1; i >= 0 && message[i] == '\\'; i--)
                {
                    escaped = !escaped;
                }
                // extract the colorcode
                char colorCode = message[startIndex + 1];
                if (Color.IsValidColorCode(colorCode) || allowNewlines && (colorCode == 'n' || colorCode == 'N'))
                {
                    if (escaped)
                    {
                        // it was escaped; remove escaping character
                        startIndex++;
                        output.Append(message, lastAppendedIndex, startIndex - lastAppendedIndex - 2);
                        lastAppendedIndex = startIndex - 1;
                    }
                    else
                    {
                        // it was not escaped; insert substitute character
                        output.Append(message, lastAppendedIndex, startIndex - lastAppendedIndex);
                        output.Append('&');
                        lastAppendedIndex = startIndex + 1;
                        startIndex       += 2;
                    }
                }
                else
                {
                    startIndex++; // unrecognized colorcode, keep going
                }
                startIndex = message.IndexOf('%', startIndex);
            }
            // append the leftovers
            output.Append(message, lastAppendedIndex, message.Length - lastAppendedIndex);
            return(output.ToString());
        }