char.IsWhiteSpace(char)

Here are the examples of the csharp api char.IsWhiteSpace(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1211 Examples 7

19 Source : AttachmentCommand.cs
with GNU Affero General Public License v3.0
from arklumpus

public override IEnumerable<(ConsoleTextSpan[], string)> GetCompletions(string partialCommand)
        {
            if (string.IsNullOrWhiteSpace(partialCommand))
            {
                yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("add", ConsoleColor.Yellow) }, "attachment add ");
                yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("delete", ConsoleColor.Yellow) }, "attachment delete ");
                yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("info", ConsoleColor.Yellow) }, "attachment info ");
                yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("list", ConsoleColor.Yellow) }, "attachment list ");
            }
            else
            {
                partialCommand = partialCommand.TrimStart();

                StringBuilder firstWordBuilder = new StringBuilder();

                foreach (char c in partialCommand)
                {
                    if (!char.IsWhiteSpace(c))
                    {
                        firstWordBuilder.Append(c);
                    }
                    else
                    {
                        break;
                    }
                }

                string firstWord = firstWordBuilder.ToString();

                if (firstWord.Equals("add", StringComparison.OrdinalIgnoreCase))
                {
                    partialCommand = partialCommand.Substring(3).TrimStart();

                    foreach ((ConsoleTextSpan[], string) item in OptionCommand.GetFileCompletion(partialCommand, "attachment " + firstWord))
                    {
                        yield return item;
                    }
                }
                else if (firstWord.Equals("list", StringComparison.OrdinalIgnoreCase))
                {
                    yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("list", ConsoleColor.Yellow) }, "attachment list ");
                }
                else if (firstWord.Equals("delete", StringComparison.OrdinalIgnoreCase))
                {
                    partialCommand = partialCommand.Substring(6).TrimStart();

                    foreach (KeyValuePair<string, Attachment> att in Program.StateData.Attachments)
                    {
                        if (att.Key.StartsWith(partialCommand, StringComparison.OrdinalIgnoreCase))
                        {
                            yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("delete ", ConsoleColor.Yellow), new ConsoleTextSpan(att.Key + " ", ConsoleColor.Blue) }, "attachment delete " + att.Key + " ");
                        }
                    }
                }
                else if (firstWord.Equals("info", StringComparison.OrdinalIgnoreCase))
                {
                    partialCommand = partialCommand.Substring(4).TrimStart();

                    foreach (KeyValuePair<string, Attachment> att in Program.StateData.Attachments)
                    {
                        if (att.Key.StartsWith(partialCommand, StringComparison.OrdinalIgnoreCase))
                        {
                            yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("info ", ConsoleColor.Yellow), new ConsoleTextSpan(att.Key + " ", ConsoleColor.Blue) }, "attachment info " + att.Key + " ");
                        }
                    }
                }
                else
                {
                    if ("add".StartsWith(partialCommand, StringComparison.OrdinalIgnoreCase))
                    {
                        yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("add", ConsoleColor.Yellow) }, "attachment add ");
                    }

                    if ("delete".StartsWith(partialCommand, StringComparison.OrdinalIgnoreCase))
                    {
                        yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("delete", ConsoleColor.Yellow) }, "attachment delete ");
                    }

                    if ("info".StartsWith(partialCommand, StringComparison.OrdinalIgnoreCase))
                    {
                        yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("info", ConsoleColor.Yellow) }, "attachment info ");
                    }

                    if ("list".StartsWith(partialCommand, StringComparison.OrdinalIgnoreCase))
                    {
                        yield return (new ConsoleTextSpan[] { new ConsoleTextSpan("attachment ", ConsoleColor.Green), new ConsoleTextSpan("list", ConsoleColor.Yellow) }, "attachment list ");
                    }
                }
            }
        }

19 Source : LoadCommand.cs
with GNU Affero General Public License v3.0
from arklumpus

public override void Execute(string command)
        {
            if (string.IsNullOrWhiteSpace(command))
            {
                if (Program.FileOpener != null)
                {
                    LoadFile(null);
                }
                else
                {
                    ConsoleWrapper.WriteLine();
                    ConsoleWrapper.WriteLine(new ConsoleTextSpan("No file has been opened!", ConsoleColor.Red));
                    ConsoleWrapper.WriteLine();
                }
            }
            else
            {
                command = command.TrimStart();

                StringBuilder firstWordBuilder = new StringBuilder();

                foreach (char c in command)
                {
                    if (!char.IsWhiteSpace(c))
                    {
                        firstWordBuilder.Append(c);
                    }
                    else
                    {
                        break;
                    }
                }

                string firstWord = firstWordBuilder.ToString();

                if (firstWord.Equals("with", StringComparison.OrdinalIgnoreCase))
                {
                    if (Program.FileOpener != null)
                    {
                        command = command.Substring(4).Trim();

                        bool found = false;

                        foreach (LoadFileModule mod in Modules.LoadFileModules)
                        {
                            if (mod.Name.Equals(command, StringComparison.OrdinalIgnoreCase) || mod.Id.Equals(command, StringComparison.OrdinalIgnoreCase))
                            {
                                LoadFile(mod.Id);
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            ConsoleWrapper.WriteLine();
                            ConsoleWrapper.WriteLine(new ConsoleTextSpan("Could not find the specified module!", ConsoleColor.Red));
                            ConsoleWrapper.WriteLine();
                        }
                    }
                    else
                    {
                        ConsoleWrapper.WriteLine();
                        ConsoleWrapper.WriteLine(new ConsoleTextSpan("No file has been opened!", ConsoleColor.Red));
                        ConsoleWrapper.WriteLine();
                    }
                }
                else if (firstWord.Equals("info", StringComparison.OrdinalIgnoreCase))
                {
                    if (Program.FileOpener != null)
                    {
                        Dictionary<string, double> info = GetLoadInfo();
                        (string, string, double)[] scores = (from el in info orderby el.Value descending select (el.Key, Modules.GetModule(Modules.LoadFileModules, el.Key).Name, el.Value)).ToArray();

                        int maxNameLength = (from el in scores select el.Item2.Length).Max() + 4;
                        int maxKeyLength = (from el in scores select el.Item1.Length).Max();
                        int maxValueLength = (from el in scores select el.Item3.ToString("0.####").Length).Max() + 4;

                        maxNameLength = Math.Max(maxNameLength, "Module name".Length + 4);
                        maxKeyLength = Math.Max(maxKeyLength, "Module id".Length);
                        maxValueLength = Math.Max(maxValueLength, "Priority".Length + 4);

                        ConsoleWrapper.WriteLine();

                        ConsoleWrapper.WriteLine(new ConsoleTextSpan[] {
                                new ConsoleTextSpan(new string(ConsoleWrapper.Whitespace, 2) + "Priority" + new string(ConsoleWrapper.Whitespace, maxValueLength - "Priority".Length), 2),
                                new ConsoleTextSpan("Module name" + new string(ConsoleWrapper.Whitespace, maxNameLength - "Module name".Length), 2),
                                new ConsoleTextSpan("Module id" + new string(ConsoleWrapper.Whitespace, maxKeyLength - "Module id".Length), 2)
                                });


                        ConsoleWrapper.WriteLine(new ConsoleTextSpan[] {
                                new ConsoleTextSpan(new string(ConsoleWrapper.Whitespace, 2) + new string('─', maxNameLength + maxKeyLength + maxValueLength), 2)
                                });


                        for (int i = 0; i < scores.Length; i++)
                        {
                            ConsoleWrapper.WriteLine(new ConsoleTextSpan[] {
                                new ConsoleTextSpan(new string(ConsoleWrapper.Whitespace, 2)),
                                new ConsoleTextSpan(scores[i].Item3.ToString("0.####") + new string(ConsoleWrapper.Whitespace, maxValueLength - scores[i].Item3.ToString("0.####").Length), 2, scores[i].Item3 <= 0 ? ConsoleColor.Red : i == 0 ? ConsoleColor.Green : ConsoleColor.Yellow),
                                new ConsoleTextSpan(scores[i].Item2 + new string(ConsoleWrapper.Whitespace, maxNameLength - scores[i].Item2.Length), 2),
                                new ConsoleTextSpan(scores[i].Item1 + new string(ConsoleWrapper.Whitespace, maxKeyLength - scores[i].Item1.Length), 2)
                                });
                        }

                        ConsoleWrapper.WriteLine();
                    }
                    else
                    {
                        ConsoleWrapper.WriteLine();
                        ConsoleWrapper.WriteLine(new ConsoleTextSpan("No file has been opened!", ConsoleColor.Red));
                        ConsoleWrapper.WriteLine();
                    }
                }
                else
                {
                    ConsoleWrapper.WriteLine();
                    ConsoleWrapper.WriteLine(new ConsoleTextSpan("Unknown action: " + command, ConsoleColor.Red));
                    ConsoleWrapper.WriteLine();
                }
            }
        }

19 Source : Commands.cs
with GNU Affero General Public License v3.0
from arklumpus

public static IEnumerable<(ConsoleTextSpan[], string)> GetCompletions(string partialCommand)
        {
            StringBuilder firstWordBuilder = new StringBuilder();

            foreach (char c in partialCommand)
            {
                if (!char.IsWhiteSpace(c))
                {
                    firstWordBuilder.Append(c);
                }
                else
                {
                    break;
                }
            }

            string firstWord = firstWordBuilder.ToString();

            if (firstWord == partialCommand)
            {
                foreach (Command command in AllAvailableCommands)
                {
                    if (command.PrimaryCommand.StartsWith(firstWord, StringComparison.OrdinalIgnoreCase))
                    {
                        yield return (new ConsoleTextSpan[] { new ConsoleTextSpan(command.PrimaryCommand, ConsoleColor.Green) }, command.PrimaryCommand + " ");
                    }
                }
            }
            else
            {
                Command whichCommand = null;

                foreach (Command command in AllAvailableCommands)
                {
                    if (command.PrimaryCommand.Equals(firstWord, StringComparison.OrdinalIgnoreCase))
                    {
                        whichCommand = command;
                    }
                }

                if (whichCommand != null)
                {
                    string restOfCommand = partialCommand.Substring(firstWord.Length);

                    List<(ConsoleTextSpan[], string)> items = new List<(ConsoleTextSpan[], string)>();

                    try
                    {
                        items.AddRange(whichCommand.GetCompletions(restOfCommand));
                    }
                    catch { }


                    foreach ((ConsoleTextSpan[], string) sr in items)
                    {
                        yield return sr;
                    }

                }
                else
                {
                    yield break;
                }
            }
        }

19 Source : Commands.cs
with GNU Affero General Public License v3.0
from arklumpus

public static bool ExecuteCommand(string command)
        {
            if (string.IsNullOrWhiteSpace(command))
            {
                return true;
            }

            StringBuilder firstWordBuilder = new StringBuilder();

            foreach (char c in command)
            {
                if (!char.IsWhiteSpace(c))
                {
                    firstWordBuilder.Append(c);
                }
                else
                {
                    break;
                }
            }

            string firstWord = firstWordBuilder.ToString();

            Command whichCommand = null;

            foreach (Command commandItem in AllAvailableCommands)
            {
                if (commandItem.PrimaryCommand.Equals(firstWord, StringComparison.OrdinalIgnoreCase))
                {
                    whichCommand = commandItem;
                }
            }

            if (whichCommand != null)
            {
                string restOfCommand = command.Substring(firstWord.Length);
                whichCommand.Execute(restOfCommand);
                return true;
            }
            else
            {
                return false;
            }
        }

19 Source : ActionWindow.xaml.cs
with GNU General Public License v3.0
from armandoalonso

private void TextEditor_TextEntering(object sender, TextCompositionEventArgs e)
        {
            if (e.Text.Length > 0 && completionWindow != null)
            {
                if (!char.IsLetterOrDigit(e.Text[0]) && !char.IsWhiteSpace(e.Text[0]) && !char.IsSymbol(e.Text[0]))
                {
                    // Whenever a non-letter is typed while the completion window is open,
                    // insert the currently selected element.
                    completionWindow.CompletionList.RequestInsertion(e);
                }
            }
            // Do not set e.Handled=true.
            // We still want to insert the character that was typed.
        }

19 Source : AddonWindow.xaml.cs
with GNU General Public License v3.0
from armandoalonso

private void AddonTextEditor_TextEntering(object sender, TextCompositionEventArgs e)
        {
            if (e.Text.Length > 0 && completionWindow != null)
            {
                if (!char.IsLetterOrDigit(e.Text[0]) && !char.IsWhiteSpace(e.Text[0]) && !char.IsSymbol(e.Text[0]))
                {
                    // Whenever a non-letter is typed while the completion window is open,
                    // insert the currently selected element.
                    completionWindow.CompletionList.RequestInsertion(e);
                }
            }
            // Do not set e.Handled=true.
            // We still want to insert the character that was typed.
        }

19 Source : ArgumentBuilder.cs
with GNU General Public License v3.0
from Artentus

private static bool ContainsSpace(string argument)
        {
            foreach (char c in argument)
            {
                if (char.IsWhiteSpace(c))
                    return true;
            }

            return false;
        }

19 Source : Command.cs
with MIT License
from AshleighAdams

internal static string EscapeArgument(string arg)
		{
			if (arg.Length == 0)
				return "\"\"";

			bool needsQuotes = false;
			foreach (char c in arg)
			{
				if (c == '\0')
					throw new ArgumentOutOfRangeException(nameof(arg), "Argument contains an invalid char that can't be escaped.");

				needsQuotes |=
					char.IsWhiteSpace(c) ||
					c == '"' ||
					c == '\'';
			}

			if (!needsQuotes)
				return arg;

			var sb = new StringBuilder(arg.Length + 2);

			int uncommittedBackslashes = 0;
			void commitBackslashes(bool escape)
			{
				if (uncommittedBackslashes == 0)
					return;

				int backslashCount = escape ?
					uncommittedBackslashes * 2 :
					uncommittedBackslashes;
				sb.Append('\\', backslashCount);
				uncommittedBackslashes = 0;
			}

			sb.Append('"');
			foreach (char c in arg)
			{
				switch (c)
				{
					case '\\':
						uncommittedBackslashes++;
						break;
					case '"':
						commitBackslashes(escape: true);
						sb.Append("\\\"");
						break;
					default:
						commitBackslashes(escape: false);
						sb.Append(c);
						break;
				}
			}
			commitBackslashes(escape: true);
			sb.Append('"');

			return sb.ToString();
		}

19 Source : CommandParser.cs
with GNU Affero General Public License v3.0
from asmejkal

public string ParseInvoker(string message, string prefix) => 
            new string(message.TakeWhile(c => !char.IsWhiteSpace(c)).Skip(prefix.Length).ToArray());

19 Source : HtmlAgilityExtensions.cs
with GNU Affero General Public License v3.0
from asmejkal

public static void Process(StringBuilder builder, ref ToPlainTextState state, params char[] chars)
        {
            foreach (var ch in chars)
            {
                if (char.IsWhiteSpace(ch))
                {
                    if (IsHardSpace(ch))
                    {
                        if (state == ToPlainTextState.WhiteSpace)
                            builder.Append(' ');
                        builder.Append(' ');
                        state = ToPlainTextState.NotWhiteSpace;
                    }
                    else
                    {
                        if (state == ToPlainTextState.NotWhiteSpace)
                            state = ToPlainTextState.WhiteSpace;
                    }
                }
                else
                {
                    if (state == ToPlainTextState.WhiteSpace)
                        builder.Append(' ');
                    builder.Append(ch);
                    state = ToPlainTextState.NotWhiteSpace;
                }
            }
        }

19 Source : StringParsingExtensions.cs
with GNU Affero General Public License v3.0
from asmejkal

public static IEnumerable<Token> Tokenize(this string value, params char[] textQualifiers)
        {
            if (string.IsNullOrEmpty(value))
                yield break;

            char prevChar = '\0', nextChar = '\0', currentChar = '\0';
            bool inString = false;
            StringBuilder token = new StringBuilder();
            int begin = -1;
            for (int i = 0; i < value.Length; i++)
            {
                currentChar = value[i];
                prevChar = i > 0 ? prevChar = value[i - 1] : '\0';
                nextChar = i + 1 < value.Length ? value[i + 1] : '\0';

                if (textQualifiers.Contains(currentChar) && (prevChar == '\0' || char.IsWhiteSpace(prevChar)) && !inString)
                {
                    inString = true;
                    if (begin < 0)
                        begin = i;

                    continue;
                }

                if (textQualifiers.Contains(currentChar) && (nextChar == '\0' || char.IsWhiteSpace(nextChar)) && inString && prevChar != '\\')
                {
                    inString = false;
                    continue;
                }

                if (char.IsWhiteSpace(currentChar) && !inString)
                {
                    if (token.Length > 0)
                    {
                        yield return new Token { Begin = begin, End = i, Value = token.ToString() };
                        token = token.Remove(0, token.Length);
                    }

                    begin = -1;
                    continue;
                }

                if (begin < 0)
                    begin = i;

                token = token.Append(currentChar);
            }

            if (token.Length > 0)
                yield return new Token { Begin = begin, End = value.Length, Value = token.ToString() };
        }

19 Source : OwinHelpers.cs
with Apache License 2.0
from aspnet

public bool MoveNext()
            {
                while (true)
                {
                    if (_mode == Mode.Produce)
                    {
                        _leadingStart = _trailingStart;
                        _leadingEnd = -1;
                        _valueStart = -1;
                        _valueEnd = -1;
                        _trailingStart = -1;

                        if (_offset == _headerLength &&
                            _leadingStart != -1 &&
                            _leadingStart != _offset)
                        {
                            // Also produce trailing whitespace
                            _leadingEnd = _offset;
                            return true;
                        }
                        _mode = Mode.Leading;
                    }

                    // if end of a string
                    if (_offset == _headerLength)
                    {
                        ++_index;
                        _offset = -1;
                        _leadingStart = 0;
                        _leadingEnd = -1;
                        _valueStart = -1;
                        _valueEnd = -1;
                        _trailingStart = -1;

                        // if that was the last string
                        if (_index == _headers.Length)
                        {
                            // no more move nexts
                            return false;
                        }

                        // grab the next string
                        _header = _headers[_index] ?? string.Empty;
                        _headerLength = _header.Length;
                    }
                    while (true)
                    {
                        ++_offset;
                        char ch = _offset == _headerLength ? (char)0 : _header[_offset];
                        // todo - array of attrs
                        Attr attr = char.IsWhiteSpace(ch) ? Attr.Whitespace : ch == '\"' ? Attr.Quote : (ch == ',' || ch == (char)0) ? Attr.Delimiter : Attr.Value;

                        switch (_mode)
                        {
                            case Mode.Leading:
                                switch (attr)
                                {
                                    case Attr.Delimiter:
                                        _leadingEnd = _offset;
                                        _mode = Mode.Produce;
                                        break;
                                    case Attr.Quote:
                                        _leadingEnd = _offset;
                                        _valueStart = _offset;
                                        _mode = Mode.ValueQuoted;
                                        break;
                                    case Attr.Value:
                                        _leadingEnd = _offset;
                                        _valueStart = _offset;
                                        _mode = Mode.Value;
                                        break;
                                    case Attr.Whitespace:
                                        // more
                                        break;
                                }
                                break;
                            case Mode.Value:
                                switch (attr)
                                {
                                    case Attr.Quote:
                                        _mode = Mode.ValueQuoted;
                                        break;
                                    case Attr.Delimiter:
                                        _valueEnd = _offset;
                                        _trailingStart = _offset;
                                        _mode = Mode.Produce;
                                        break;
                                    case Attr.Value:
                                        // more
                                        break;
                                    case Attr.Whitespace:
                                        _valueEnd = _offset;
                                        _trailingStart = _offset;
                                        _mode = Mode.Trailing;
                                        break;
                                }
                                break;
                            case Mode.ValueQuoted:
                                switch (attr)
                                {
                                    case Attr.Quote:
                                        _mode = Mode.Value;
                                        break;
                                    case Attr.Delimiter:
                                        if (ch == (char)0)
                                        {
                                            _valueEnd = _offset;
                                            _trailingStart = _offset;
                                            _mode = Mode.Produce;
                                        }
                                        break;
                                    case Attr.Value:
                                    case Attr.Whitespace:
                                        // more
                                        break;
                                }
                                break;
                            case Mode.Trailing:
                                switch (attr)
                                {
                                    case Attr.Delimiter:
                                        _mode = Mode.Produce;
                                        break;
                                    case Attr.Quote:
                                        // back into value
                                        _trailingStart = -1;
                                        _valueEnd = -1;
                                        _mode = Mode.ValueQuoted;
                                        break;
                                    case Attr.Value:
                                        // back into value
                                        _trailingStart = -1;
                                        _valueEnd = -1;
                                        _mode = Mode.Value;
                                        break;
                                    case Attr.Whitespace:
                                        // more
                                        break;
                                }
                                break;
                        }
                        if (_mode == Mode.Produce)
                        {
                            return true;
                        }
                    }
                }
            }

19 Source : OwinHelpers.cs
with Apache License 2.0
from aspnet

internal static void ParseDelimited(string text, char[] delimiters, Action<string, string, object> callback, bool decodePlus, bool decodeKey, object state)
        {
            int textLength = text.Length;
            int equalIndex = text.IndexOf('=');
            if (equalIndex == -1)
            {
                equalIndex = textLength;
            }
            int scanIndex = 0;
            while (scanIndex < textLength)
            {
                int delimiterIndex = text.IndexOfAny(delimiters, scanIndex);
                if (delimiterIndex == -1)
                {
                    delimiterIndex = textLength;
                }
                if (equalIndex < delimiterIndex)
                {
                    while (scanIndex != equalIndex && char.IsWhiteSpace(text[scanIndex]))
                    {
                        ++scanIndex;
                    }
                    string name = text.Substring(scanIndex, equalIndex - scanIndex);
                    string value = text.Substring(equalIndex + 1, delimiterIndex - equalIndex - 1);
                    if (decodePlus)
                    {
                        name = name.Replace('+', ' ');
                        value = value.Replace('+', ' ');
                    }
                    if (decodeKey)
                    {
                        name = Uri.UnescapeDataString(name);
                    }
                    value = Uri.UnescapeDataString(value);
                    callback(name, value, state);
                    equalIndex = text.IndexOf('=', delimiterIndex);
                    if (equalIndex == -1)
                    {
                        equalIndex = textLength;
                    }
                }
                scanIndex = delimiterIndex + 1;
            }
        }

19 Source : WsFederationAuthenticationHandler.cs
with Apache License 2.0
from aspnet

private static IDictionary<string, List<string>> ParseDelimited(string text)
        {
            char[] delimiters = new[] { '&', ';' };
            var acreplacedulator = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
            int textLength = text.Length;
            int equalIndex = text.IndexOf('=');
            if (equalIndex == -1)
            {
                equalIndex = textLength;
            }
            int scanIndex = 0;
            while (scanIndex < textLength)
            {
                int delimiterIndex = text.IndexOfAny(delimiters, scanIndex);
                if (delimiterIndex == -1)
                {
                    delimiterIndex = textLength;
                }
                if (equalIndex < delimiterIndex)
                {
                    while (scanIndex != equalIndex && char.IsWhiteSpace(text[scanIndex]))
                    {
                        ++scanIndex;
                    }
                    string name = text.Substring(scanIndex, equalIndex - scanIndex);
                    string value = text.Substring(equalIndex + 1, delimiterIndex - equalIndex - 1);

                    name = Uri.UnescapeDataString(name.Replace('+', ' '));
                    value = Uri.UnescapeDataString(value.Replace('+', ' '));

                    List<string> existing;
                    if (!acreplacedulator.TryGetValue(name, out existing))
                    {
                        acreplacedulator.Add(name, new List<string>(1) { value });
                    }
                    else
                    {
                        existing.Add(value);
                    }

                    equalIndex = text.IndexOf('=', delimiterIndex);
                    if (equalIndex == -1)
                    {
                        equalIndex = textLength;
                    }
                }
                scanIndex = delimiterIndex + 1;
            }
            return acreplacedulator;
        }

19 Source : WordSplitter.cs
with MIT License
from aspose-pdf

public static string[] ConvertHtmlToListOfWords(
            string text,
            IList<Regex> blockExpressions)
        {
            var mode = Mode.Character;
            var currentWord = new List<char>();
            var words = new List<string>();
            var blockLocations = FindBlocks(text, blockExpressions);
            var isBlockCheckRequired = blockLocations.Any();
            var isGrouping = false;
            var groupingUntil = -1;

            for (var index = 0; index < text.Length; index++)
            {
                var character = text[index];

                // Don't bother executing block checks if we don't have any blocks to check for!
                if (isBlockCheckRequired)
                {
                    // Check if we have completed grouping a text sequence/block
                    if (groupingUntil == index)
                    {
                        groupingUntil = -1;
                        isGrouping = false;
                    }

                    // Check if we need to group the next text sequence/block
                    int until = 0;
                    if (blockLocations.TryGetValue(index, out until))
                    {
                        isGrouping = true;
                        groupingUntil = until;
                    }

                    // if we are grouping, then we don't care about what type of character we have, it's going to be treated as a word
                    if (isGrouping)
                    {
                        currentWord.Add(character);
                        mode = Mode.Character;
                        continue;
                    }
                }

                switch (mode)
                {
                    case Mode.Character:

                        if (Utils.IsStartOfTag(character))
                        {
                            if (currentWord.Count != 0)
                            {
                                words.Add(new string(currentWord.ToArray()));
                            }

                            currentWord.Clear();
                            currentWord.Add('<');
                            mode = Mode.Tag;
                        }
                        else if (Utils.IsStartOfEnreplacedy(character))
                        {
                            if (currentWord.Count != 0)
                            {
                                words.Add(new string(currentWord.ToArray()));
                            }

                            currentWord.Clear();
                            currentWord.Add(character);
                            mode = Mode.Enreplacedy;
                        }
                        else if (Utils.IsWhiteSpace(character))
                        {
                            if (currentWord.Count != 0)
                            {
                                words.Add(new string(currentWord.ToArray()));
                            }
                            currentWord.Clear();
                            currentWord.Add(character);
                            mode = Mode.Whitespace;
                        }
                        else if (Utils.IsWord(character)
                            && (currentWord.Count == 0 || Utils.IsWord(currentWord.Last())))
                        {
                            currentWord.Add(character);
                        }
                        else
                        {
                            if (currentWord.Count != 0)
                            {
                                words.Add(new string(currentWord.ToArray()));
                            }
                            currentWord.Clear();
                            currentWord.Add(character);
                        }

                        break;
                    case Mode.Tag:

                        if (Utils.IsEndOfTag(character))
                        {
                            currentWord.Add(character);
                            words.Add(new string(currentWord.ToArray()));
                            currentWord.Clear();

                            mode = Utils.IsWhiteSpace(character) ? Mode.Whitespace : Mode.Character;
                        }
                        else
                        {
                            currentWord.Add(character);
                        }

                        break;
                    case Mode.Whitespace:

                        if (Utils.IsStartOfTag(character))
                        {
                            if (currentWord.Count != 0)
                            {
                                words.Add(new string(currentWord.ToArray()));
                            }
                            currentWord.Clear();
                            currentWord.Add(character);
                            mode = Mode.Tag;
                        }
                        else if (Utils.IsStartOfEnreplacedy(character))
                        {
                            if (currentWord.Count != 0)
                            {
                                words.Add(new string(currentWord.ToArray()));
                            }

                            currentWord.Clear();
                            currentWord.Add(character);
                            mode = Mode.Enreplacedy;
                        }
                        else if (Utils.IsWhiteSpace(character))
                        {
                            currentWord.Add(character);
                        }
                        else
                        {
                            if (currentWord.Count != 0)
                            {
                                words.Add(new string(currentWord.ToArray()));
                            }

                            currentWord.Clear();
                            currentWord.Add(character);
                            mode = Mode.Character;
                        }

                        break;
                    case Mode.Enreplacedy:
                        if (Utils.IsStartOfTag(character))
                        {
                            if (currentWord.Count != 0)
                            {
                                words.Add(new string(currentWord.ToArray()));
                            }

                            currentWord.Clear();
                            currentWord.Add(character);
                            mode = Mode.Tag;
                        }
                        else if (char.IsWhiteSpace(character))
                        {
                            if (currentWord.Count != 0)
                            {
                                words.Add(new string(currentWord.ToArray()));
                            }
                            currentWord.Clear();
                            currentWord.Add(character);
                            mode = Mode.Whitespace;
                        }
                        else if (Utils.IsEndOfEnreplacedy(character))
                        {
                            var switchToNextMode = true;
                            if (currentWord.Count != 0)
                            {
                                currentWord.Add(character);
                                words.Add(new string(currentWord.ToArray()));

                                //join   enreplacedy with last whitespace
                                if (words.Count > 2
                                    && Utils.IsWhiteSpace(words[words.Count - 2])
                                    && Utils.IsWhiteSpace(words[words.Count - 1]))
                                {
                                    var w1 = words[words.Count - 2];
                                    var w2 = words[words.Count - 1];
                                    words.RemoveRange(words.Count - 2, 2);
                                    currentWord.Clear();
                                    currentWord.AddRange(w1);
                                    currentWord.AddRange(w2);
                                    mode = Mode.Whitespace;
                                    switchToNextMode = false;
                                }
                            }
                            if (switchToNextMode)
                            {
                                currentWord.Clear();
                                mode = Mode.Character;
                            }
                        }
                        else if (Utils.IsWord(character))
                        {
                            currentWord.Add(character);
                        }
                        else
                        {
                            if (currentWord.Count != 0)
                            {
                                words.Add(new string(currentWord.ToArray()));
                            }
                            currentWord.Clear();
                            currentWord.Add(character);
                            mode = Mode.Character;
                        }
                        break;
                }
            }
            if (currentWord.Count != 0)
            {
                words.Add(new string(currentWord.ToArray()));
            }

            return words.ToArray();
        }

19 Source : Utils.cs
with MIT License
from aspose-pdf

public static bool IsWhiteSpace(char value)
        {
            return char.IsWhiteSpace(value);
        }

19 Source : DefaultState.cs
with MIT License
from ASStoredProcedures

public ITokenizerState Exec(char currentChar, int position, string statement, ref StringBuilder token, List<Token> tokens)
        {
            if (char.IsWhiteSpace(currentChar))
            {
                if (token.Length > 0)
                {
                    tokens.Add(new Token(token.ToString()));
                    token = new StringBuilder();
                }
                return new WhiteSpaceState();
            }
            if (InStringState.IsStringDelimiter(currentChar))
            {
                return new InStringState();
            }
            if (InCommentState.IsCommentStart(currentChar,position>0?statement[position-1]:'\x0000'))
            {
                return new InCommentState(statement.Substring(position-1,2));
            }
            switch (currentChar)
            {
                case '(':
                case ')':
                case '[':
                case ']':
                case '=': // an equals sign that is not inside string quotes should trigger a new token
                case ',': // add commas to their own token
       
                    if (token.Length > 0)
                    {
                        tokens.Add(new Token(token.ToString()));
                        token = new StringBuilder();
                    }
                    tokens.Add(new Token(currentChar.ToString(),TokenType.Comma));
                    break;
                default:
                    //else add the current char to the string builder
                    token.Append(currentChar);
                    break;
            }
            return this; // stay in default state
        }

19 Source : WhiteSpaceState.cs
with MIT License
from ASStoredProcedures

public ITokenizerState Exec(char currentChar, int position, string statement, ref StringBuilder token, List<Token> tokens)
        {
            if (char.IsWhiteSpace(currentChar) || char.IsControl(currentChar))
            {
                return this; // stay in Whitespace state
            }
            if (InStringState.IsStringDelimiter(currentChar))
            {
                return new InStringState();
            }
            ITokenizerState defState = new DefaultState();
            defState.Exec(currentChar, position, statement,ref token, tokens);
            return defState;
        }

19 Source : KeyValue.cs
with MIT License
from Astropilot

private void EatWhiteSpace()
        {
            while (!EndOfStream)
            {
                if (!char.IsWhiteSpace((char)Peek()))
                {
                    break;
                }

                Read();
            }
        }

19 Source : KeyValue.cs
with MIT License
from Astropilot

public string ReadToken(out bool wasQuoted, out bool wasConditional)
        {
            wasQuoted = false;
            wasConditional = false;

            while (true)
            {
                EatWhiteSpace();

                if (EndOfStream)
                {
                    return null;
                }

                if (!EatCPPComment())
                {
                    break;
                }
            }

            if (EndOfStream)
            {
                return null;
            }

            char next = (char)Peek();
            if (next == '"')
            {
                wasQuoted = true;

                // "
                Read();

                var sb = new StringBuilder();
                while (!EndOfStream)
                {
                    if (Peek() == '\\')
                    {
                        Read();

                        char escapedChar = (char)Read();
                        if (s_escapedMapping.TryGetValue(escapedChar, out char replacedChar))
                        {
                            sb.Append(replacedChar);
                        }
                        else
                        {
                            sb.Append(escapedChar);
                        }

                        continue;
                    }

                    if (Peek() == '"')
                    {
                        break;
                    }

                    sb.Append((char)Read());
                }

                // "
                Read();

                return sb.ToString();
            }

            if (next == '{' || next == '}')
            {
                Read();
                return next.ToString();
            }

            bool bConditionalStart = false;
            int count = 0;
            var ret = new StringBuilder();
            while (!EndOfStream)
            {
                next = (char)Peek();

                if (next == '"' || next == '{' || next == '}')
                {
                    break;
                }

                if (next == '[')
                {
                    bConditionalStart = true;
                }

                if (next == ']' && bConditionalStart)
                {
                    wasConditional = true;
                }

                if (char.IsWhiteSpace(next))
                {
                    break;
                }

                if (count < 1023)
                {
                    ret.Append(next);
                }
                else
                {
                    throw new Exception("ReadToken overflow");
                }

                Read();
            }

            return ret.ToString();
        }

19 Source : NDesk.Options.cs
with Apache License 2.0
from atifaziz

private static IEnumerable<string> GetLines (string description)
		{
			if (string.IsNullOrEmpty (description)) {
				yield return string.Empty;
				yield break;
			}
			int length = 80 - OptionWidth - 1;
			int start = 0, end;
			do {
				end = GetLineEnd (start, length, description);
				char c = description [end-1];
				if (char.IsWhiteSpace (c))
					--end;
				bool writeContinuation = end != description.Length && !IsEolChar (c);
				string line = description.Substring (start, end - start) +
						(writeContinuation ? "-" : "");
				yield return line;
				start = end;
				if (char.IsWhiteSpace (c))
					++start;
				length = 80 - OptionWidth - 2 - 1;
			} while (end < description.Length);
		}

19 Source : Tokeniser.cs
with MIT License
from atifaziz

State GetDirectiveValue ()
        {
            int start = position;
            int delimiter = '\0';
            for (; position < content.Length; position++) {
                char c = content[position];
                nextStateLocation = nextStateLocation.AddCol ();
                if (c == '\r') {
                    if (position + 1 < content.Length && content[position + 1] == '\n')
                        position++;
                    nextStateLocation = nextStateLocation.AddLine();
                } else if (c == '\n')
                    nextStateLocation = nextStateLocation.AddLine();
                if (delimiter == '\0') {
                    if (c == '\'' || c == '"') {
                        start = position;
                        delimiter = c;
                    } else if (!Char.IsWhiteSpace (c)) {
                        throw new ParserException ("Unexpected character '" + c + "'. Expecting attribute value.", nextStateLocation);
                    }
                    continue;
                }
                if (c == delimiter) {
                    value = content.Substring (start + 1, position - start - 1);
                    position++;
                    return State.Directive;
                }
            }
            throw new ParserException ("Unexpected end of file.", nextStateLocation);
        }

19 Source : Tokeniser.cs
with MIT License
from atifaziz

State NextStateInDirective () {
            for (; position < content.Length; position++) {
                char c = content[position];
                if (c == '\r') {
                    if (position + 1 < content.Length && content[position + 1] == '\n')
                        position++;
                    nextStateLocation = nextStateLocation.AddLine();
                } else if (c == '\n') {
                    nextStateLocation = nextStateLocation.AddLine();
                } else if (Char.IsLetter (c)) {
                    return State.DirectiveName;
                } else if (c == '=') {
                    nextStateLocation = nextStateLocation.AddCol ();
                    position++;
                    return State.DirectiveValue;
                } else if (c == '#' && position + 1 < content.Length && content[position+1] == '>') {
                    position+=2;
                    TagEndLocation = nextStateLocation.AddCols (2);
                    nextStateLocation = nextStateLocation.AddCols (3);

                    //skip newlines directly after directives
                    if ((position += IsNewLine()) > 0) {
                        nextStateLocation = nextStateLocation.AddLine();
                    }

                    return State.Content;
                } else if (!Char.IsWhiteSpace (c)) {
                    throw new ParserException ("Directive ended unexpectedly with character '" + c + "'", nextStateLocation);
                } else {
                    nextStateLocation = nextStateLocation.AddCol ();
                }
            }
            throw new ParserException ("Unexpected end of file.", nextStateLocation);
        }

19 Source : Options.cs
with MIT License
from atifaziz

private static List<string> GetLines (string description)
        {
            List<string> lines = new List<string> ();
            if (string.IsNullOrEmpty (description)) {
                lines.Add (string.Empty);
                return lines;
            }
            int length = 80 - OptionWidth - 2;
            int start = 0, end;
            do {
                end = GetLineEnd (start, length, description);
                bool cont = false;
                if (end < description.Length) {
                    char c = description [end];
                    if (c == '-' || (char.IsWhiteSpace (c) && c != '\n'))
                        ++end;
                    else if (c != '\n') {
                        cont = true;
                        --end;
                    }
                }
                lines.Add (description.Substring (start, end - start));
                if (cont) {
                    lines [lines.Count-1] += "-";
                }
                start = end;
                if (start < description.Length && description [start] == '\n')
                    ++start;
            } while (end < description.Length);
            return lines;
        }

19 Source : Compiler.cs
with GNU General Public License v3.0
from AtomCrafty

[DebuggerStepThrough]
		void SkipWhitespace(BinaryReader br) {
			while(char.IsWhiteSpace((char)br.PeekChar())) {
				br.ReadChar();
			}
		}

19 Source : TextUtils.cs
with GNU General Public License v3.0
from AtomCrafty

public static string[] WrapWords(string source, int lineWidth, FontMetrics metrics) {
			int pos = 0;
			int lastWrap = 0;
			int lastPossibleWrap = 0;
			int curWidth = 0;
			List<string> lines = new List<string>();

			while(pos < source.Length) {
				char ch = source[pos];
				int charWidth = metrics.GetCharacterWidth(ch);

				if(ch == '\n') {
					// wrap here
					string line = source.Substring(lastWrap, pos - lastWrap);
					lastWrap = lastPossibleWrap = pos;
					curWidth = 0;

					lines.Add(line.PadRight(line.Length + (lineWidth - StringWidth(line, metrics)) / metrics.HalfWidthHorizontalSpacing));
				}
				else if(curWidth + charWidth > lineWidth) {
					if(lastPossibleWrap > lastWrap) {
						// check length of current word
						int end = pos;
						while(end < source.Length && !char.IsWhiteSpace(source[end]) && !IsFullWidthCharacter(source[end])) end++;
						string curWord = source.Substring(lastPossibleWrap, end - lastPossibleWrap).Trim();

						if(StringWidth(curWord, metrics) > lineWidth) {
							// word wouldn't fit in its own line, so we keep its start on the current one and force a hard wrap (no padding)
							lines.Add(source.Substring(lastWrap, pos - lastWrap));
							lastWrap = lastPossibleWrap = pos;
							curWidth = 0;
						}
						else {
							// push the current word to the next line
							string line = source.Substring(lastWrap, lastPossibleWrap - lastWrap);
							int curLineWidth = StringWidth(line, metrics);
							lastWrap = lastPossibleWrap;
							curWidth -= curLineWidth;

							// pad and add line
							lines.Add(line.PadRight(line.Length + (lineWidth - curLineWidth) / metrics.HalfWidthHorizontalSpacing));
						}
					}
					else {
						// force a hard wrap here (no padding)
						lines.Add(source.Substring(lastWrap, pos - lastWrap));
						lastWrap = lastPossibleWrap = pos;
						curWidth = 0;
					}
				}

				curWidth += charWidth;

				pos++;

				// allow soft wraps after each full-width character
				if(char.IsWhiteSpace(ch) || IsFullWidthCharacter(ch)) {
					lastPossibleWrap = pos;
				}
			}

			// add the last line
			if(pos > lastWrap) {
				string line = source.Substring(lastWrap, pos - lastWrap);
				if(line.Trim().Length > 0) {
					lines.Add(line.PadRight(line.Length + (lineWidth - StringWidth(line, metrics)) / metrics.HalfWidthHorizontalSpacing));
				}
			}

			return lines.ToArray();
		}

19 Source : StringReader.cs
with MIT License
from AtomicBlom

public void SkipWhitespace()
		{
			while (CanRead() && char.IsWhiteSpace(Peek()))
			{
				Skip();
			}
		}

19 Source : UnicodeCategoryRangesGenerator.cs
with MIT License
from AutomataDotNet

private static void WriteRangeFields(BitWidth encoding, StreamWriter sw, string field)
        {
            int bits = (int)encoding;
            int maxChar = (1 << bits) - 1;
            var catMap = new Dictionary<UnicodeCategory, Ranges>();
            for (int c = 0; c < 30; c++)
                catMap[(UnicodeCategory)c] = new Ranges();
            Ranges whitespace = new Ranges();
            Ranges wordcharacter = new Ranges();
            for (int i = 0; i <= maxChar; i++)
            {
                char ch = (char)i;
                if (char.IsWhiteSpace(ch))
                    whitespace.Add(i);
                UnicodeCategory cat = char.GetUnicodeCategory(ch);
                catMap[cat].Add(i);
                int catCode = (int)cat;
                //in .NET 3.5 
                if (bits == 7)
                    if (catCode == 0 || catCode == 1 || catCode == 2 || catCode == 3 || catCode == 4 || catCode == 5 || catCode == 8 || catCode == 18)
                        wordcharacter.Add(i);
            }
            //generate bdd reprs for each of the category ranges
            BDD[] catBDDs = new BDD[30];
            CharSetSolver bddb = new CharSetSolver(encoding);
            for (int c = 0; c < 30; c++)
                catBDDs[c] = bddb.MkBddForIntRanges(catMap[(UnicodeCategory)c].ranges);

            BDD whitespaceBdd = bddb.MkBddForIntRanges(whitespace.ranges);

            //in .NET 3.5 category 5 was NOT a word character
            //union of categories 0,1,2,3,4,8,18
            BDD wordCharBdd = bddb.MkOr(catBDDs[0],
                              bddb.MkOr(catBDDs[1],
                              bddb.MkOr(catBDDs[2],
                              bddb.MkOr(catBDDs[3],
                              bddb.MkOr(catBDDs[4],
                              bddb.MkOr(catBDDs[5],
                              bddb.MkOr(catBDDs[8], catBDDs[18])))))));
            if (bits == 7)
            {
                sw.WriteLine(@"/// <summary>
/// Array of 30 UnicodeCategory ranges. Each entry is a pair of integers. 
/// corresponding to the lower and upper bounds of the unicodes of the characters
/// that have the given UnicodeCategory code (between 0 and 29).
/// </summary>");
                sw.WriteLine("public static int[][][] " + field + " = new int[][][]{");
                foreach (UnicodeCategory c in catMap.Keys)
                {
                    sw.WriteLine("//{0}({1}):", c, (int)c);
                    if (catMap[c].Count == 0)
                        sw.WriteLine("null,");
                    else
                    {
                        sw.WriteLine("new int[][]{");
                        foreach (int[] range in catMap[c].ranges)
                            sw.WriteLine("    new int[]{" + string.Format("{0},{1}", range[0], range[1]) + "},");
                        sw.WriteLine("},");
                    }
                }
                sw.WriteLine("};");
            }

            sw.WriteLine(@"/// <summary>
/// Compact BDD encodings of the categories.
/// </summary>");
            sw.WriteLine("public static int[][] " + field + "Bdd = new int[][]{");
            foreach (UnicodeCategory c in catMap.Keys)
            {
                sw.WriteLine("//{0}({1}):", c, (int)c);
                BDD catBdd = catBDDs[(int)c];
                if (catBdd == null || catBdd.IsEmpty)
                    sw.WriteLine("null, //false");
                else if (catBdd.IsFull)
                    sw.WriteLine("new int[]{0,0}, //true");
                else
                {
                    sw.WriteLine("new int[]{");
                    foreach (var arc in bddb.SerializeCompact(catBdd))
                        sw.WriteLine("{0},", arc);
                    sw.WriteLine("},");
                }
            }
            sw.WriteLine("};");

            if (bits == 7)
            {
                sw.WriteLine(@"/// <summary>
/// Whitespace character ranges.
/// </summary>");
                sw.WriteLine("public static int[][] " + field + "Whitespace = new int[][]{");
                foreach (int[] range in whitespace.ranges)
                    sw.WriteLine("    new int[]{" + string.Format("{0},{1}", range[0], range[1]) + "},");
                sw.WriteLine("};");

                sw.WriteLine(@"/// <summary>
/// Word character ranges.
/// </summary>");
                sw.WriteLine("public static int[][] " + field + "WordCharacter = new int[][]{");
                foreach (int[] range in wordcharacter.ranges)
                    sw.WriteLine("    new int[]{" + string.Format("{0},{1}", range[0], range[1]) + "},");
                sw.WriteLine("};");
            }

            sw.WriteLine(@"/// <summary>
/// Compact BDD encoding of the whitespace characters.
/// </summary>");
            sw.WriteLine("public static int[] " + field + "WhitespaceBdd = new int[]{");
            foreach (var arc in bddb.SerializeCompact(whitespaceBdd))
                sw.WriteLine("{0},", arc);
            sw.WriteLine("};");

            sw.WriteLine(@"/// <summary>
/// Compact BDD encoding of word characters
/// </summary>");
            sw.WriteLine("public static int[] " + field + "WordCharacterBdd = new int[]{");
            foreach (var arc in bddb.SerializeCompact(wordCharBdd))
                sw.WriteLine("{0},", arc);
            sw.WriteLine("};");
        }

19 Source : IndentationReformatter.cs
with MIT License
from AvaloniaUI

public void Step(IDoreplacedentAccessor doc, IndentationSettings set)
        {
            var line = doc.Text;
            if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
            line = line.TrimStart();

            var indent = new StringBuilder();
            if (line.Length == 0)
            {
                // Special treatment for empty lines:
                if (_blockComment || (_inString && _verbatim))
                    return;
                indent.Append(_block.InnerIndent);
                indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
                
                if (doc.Text != indent.ToString())
                    doc.Text = indent.ToString();
                return;
            }

            if (TrimEnd(doc))
                line = doc.Text.TrimStart();

            var oldBlock = _block;
            var startInComment = _blockComment;
            var startInString = (_inString && _verbatim);

            #region Parse char by char
            _lineComment = false;
            _inChar = false;
            _escape = false;
            if (!_verbatim) _inString = false;

            _lastRealChar = '\n';

            var c = ' ';
            var nextchar = line[0];
            for (var i = 0; i < line.Length; i++)
            {
                if (_lineComment) break; // cancel parsing current line

                var lastchar = c;
                c = nextchar;
                nextchar = i + 1 < line.Length ? line[i + 1] : '\n';

                if (_escape)
                {
                    _escape = false;
                    continue;
                }

                #region Check for comment/string chars
                switch (c)
                {
                    case '/':
                        if (_blockComment && lastchar == '*')
                            _blockComment = false;
                        if (!_inString && !_inChar)
                        {
                            if (!_blockComment && nextchar == '/')
                                _lineComment = true;
                            if (!_lineComment && nextchar == '*')
                                _blockComment = true;
                        }
                        break;
                    case '#':
                        if (!(_inChar || _blockComment || _inString))
                            _lineComment = true;
                        break;
                    case '"':
                        if (!(_inChar || _lineComment || _blockComment))
                        {
                            _inString = !_inString;
                            if (!_inString && _verbatim)
                            {
                                if (nextchar == '"')
                                {
                                    _escape = true; // skip escaped quote
                                    _inString = true;
                                }
                                else
                                {
                                    _verbatim = false;
                                }
                            }
                            else if (_inString && lastchar == '@')
                            {
                                _verbatim = true;
                            }
                        }
                        break;
                    case '\'':
                        if (!(_inString || _lineComment || _blockComment))
                        {
                            _inChar = !_inChar;
                        }
                        break;
                    case '\\':
                        if ((_inString && !_verbatim) || _inChar)
                            _escape = true; // skip next character
                        break;
                }
                #endregion

                if (_lineComment || _blockComment || _inString || _inChar)
                {
                    if (_wordBuilder.Length > 0)
                        _block.LastWord = _wordBuilder.ToString();
                    _wordBuilder.Length = 0;
                    continue;
                }

                if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
                {
                    if (_block.Bracket == '{')
                        _block.Continuation = true;
                }

                if (char.IsLetterOrDigit(c))
                {
                    _wordBuilder.Append(c);
                }
                else
                {
                    if (_wordBuilder.Length > 0)
                        _block.LastWord = _wordBuilder.ToString();
                    _wordBuilder.Length = 0;
                }

                #region Push/Pop the blocks
                switch (c)
                {
                    case '{':
                        _block.ResetOneLineBlock();
                        _blocks.Push(_block);
                        _block.StartLine = doc.LineNumber;
                        if (_block.LastWord == "switch")
                        {
                            _block.Indent(set.IndentString + set.IndentString);
                            /* oldBlock refers to the previous line, not the previous block
							 * The block we want is not available anymore because it was never pushed.
							 * } else if (oldBlock.OneLineBlock) {
							// Inside a one-line-block is another statement
							// with a full block: indent the inner full block
							// by one additional level
							block.Indent(set, set.IndentString + set.IndentString);
							block.OuterIndent += set.IndentString;
							// Indent current line if it starts with the '{' character
							if (i == 0) {
								oldBlock.InnerIndent += set.IndentString;
							}*/
                        }
                        else
                        {
                            _block.Indent(set);
                        }
                        _block.Bracket = '{';
                        break;
                    case '}':
                        while (_block.Bracket != '{')
                        {
                            if (_blocks.Count == 0) break;
                            _block = _blocks.Pop();
                        }
                        if (_blocks.Count == 0) break;
                        _block = _blocks.Pop();
                        _block.Continuation = false;
                        _block.ResetOneLineBlock();
                        break;
                    case '(':
                    case '[':
                        _blocks.Push(_block);
                        if (_block.StartLine == doc.LineNumber)
                            _block.InnerIndent = _block.OuterIndent;
                        else
                            _block.StartLine = doc.LineNumber;
                        _block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
                                     (oldBlock.Continuation ? set.IndentString : "") +
                                     (i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
                        _block.Bracket = c;
                        break;
                    case ')':
                        if (_blocks.Count == 0) break;
                        if (_block.Bracket == '(')
                        {
                            _block = _blocks.Pop();
                            if (IsSingleStatementKeyword(_block.LastWord))
                                _block.Continuation = false;
                        }
                        break;
                    case ']':
                        if (_blocks.Count == 0) break;
                        if (_block.Bracket == '[')
                            _block = _blocks.Pop();
                        break;
                    case ';':
                    case ',':
                        _block.Continuation = false;
                        _block.ResetOneLineBlock();
                        break;
                    case ':':
                        if (_block.LastWord == "case"
                            || line.StartsWith("case ", StringComparison.Ordinal)
                            || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
                        {
                            _block.Continuation = false;
                            _block.ResetOneLineBlock();
                        }
                        break;
                }

                if (!char.IsWhiteSpace(c))
                {
                    // register this char as last char
                    _lastRealChar = c;
                }
                #endregion
            }
            #endregion

            if (_wordBuilder.Length > 0)
                _block.LastWord = _wordBuilder.ToString();
            _wordBuilder.Length = 0;

            if (startInString) return;
            if (startInComment && line[0] != '*') return;
            if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
                return;

            if (line[0] == '}')
            {
                indent.Append(oldBlock.OuterIndent);
                oldBlock.ResetOneLineBlock();
                oldBlock.Continuation = false;
            }
            else
            {
                indent.Append(oldBlock.InnerIndent);
            }

            if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
            {
                indent.Remove(indent.Length - 1, 1);
            }
            else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
            {
                indent.Remove(indent.Length - 1, 1);
            }

            if (line[0] == ':')
            {
                oldBlock.Continuation = true;
            }
            else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
            {
                if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
                    indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
            }
            else if (_lastRealChar == ')')
            {
                if (IsSingleStatementKeyword(_block.LastWord))
                {
                    _block.OneLineBlock++;
                }
            }
            else if (_lastRealChar == 'e' && _block.LastWord == "else")
            {
                _block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
                _block.Continuation = false;
                oldBlock.OneLineBlock = _block.OneLineBlock - 1;
            }

            if (doc.IsReadOnly)
            {
                // We can't change the current line, but we should accept the existing
                // indentation if possible (=if the current statement is not a multiline
                // statement).
                if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
                    oldBlock.StartLine == _block.StartLine &&
                    _block.StartLine < doc.LineNumber && _lastRealChar != ':')
                {
                    // use indent StringBuilder to get the indentation of the current line
                    indent.Length = 0;
                    line = doc.Text; // get untrimmed line
                    foreach (var t in line)
                    {
                        if (!char.IsWhiteSpace(t))
                            break;
                        indent.Append(t);
                    }
                    // /* */ multiline comments have an extra space - do not count it
                    // for the block's indentation.
                    if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
                    {
                        indent.Length -= 1;
                    }
                    _block.InnerIndent = indent.ToString();
                }
                return;
            }

            if (line[0] != '{')
            {
                if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
                    indent.Append(set.IndentString);
                indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
            }

            // this is only for blockcomment lines starting with *,
            // all others keep their old indentation
            if (startInComment)
                indent.Append(' ');

            if (indent.Length != (doc.Text.Length - line.Length) ||
                !doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
                char.IsWhiteSpace(doc.Text[indent.Length]))
            {
                doc.Text = indent + line;
            }
        }

19 Source : SqlObjectReader.cs
with MIT License
from Avanade

private void Parse()
        {
            Token? token = null;

            while (true)
            {
                var txt = _tr.ReadLine();
                if (txt == null)
                    break;

                _lines.Add(txt);
                if (_tokens.Count >= 3)
                    continue;

                // Remove comments.
                if (txt.StartsWith("--", StringComparison.InvariantCulture))
                    continue;

                var ci = txt.IndexOf("--", StringComparison.InvariantCulture);
                if (ci >= 0)
                    txt = txt.Substring(0, ci - 1).TrimEnd();

                // Remove function component.
                ci = txt.IndexOf("(", StringComparison.InvariantCulture);
                if (ci >= 0)
                    txt = txt.Substring(0, ci - 1).TrimEnd();

                // Parse out the token(s).
                var col = 0;
                for (; col < txt.Length; col++)
                {
                    if (char.IsWhiteSpace(txt[col]))
                    {
                        if (token != null)
                        {
                            token.Value = txt[token.Column..col];
                            _tokens.Add(token);
                            token = null;
                        }
                    }
                    else if (token == null)
                    {
                        token = new Token { Line = _lines.Count - 1, Column = col };
                    }
                }

                if (token != null)
                {
                    token.Value = txt[token.Column..col];
                    _tokens.Add(token);
                    token = null;
                }
            }

            ErrorMessage = CreateErrorMessage();
        }

19 Source : ParagraphRenderer.cs
with MIT License
from AVPolyakov

private static IEnumerable<DrawTextPart> GetDrawTextParts(string text)
        {
            var previousSpaceIndex = -1;
            for (var i = 0; i < text.Length; i++)
                if (char.IsWhiteSpace(text[i]))
                {
                    if (i - previousSpaceIndex - 1 > 0)
                        yield return new DrawTextPart.Word(text.Substring(previousSpaceIndex + 1, i - previousSpaceIndex - 1));
                    yield return new DrawTextPart.Space(text[i]);
                    previousSpaceIndex = i;
                }
            if (previousSpaceIndex + 1 < text.Length)
                yield return new DrawTextPart.Word(text.Substring(previousSpaceIndex + 1));
        }

19 Source : ParagraphRenderer.cs
with MIT License
from AVPolyakov

private static bool IsLineBreakChar(char c) => char.IsWhiteSpace(c) && c != '\u00A0';

19 Source : SessionManager.cs
with Apache License 2.0
from awslabs

private static bool ShouldIgnoreConfigFile(string file)
        {
            // Config files must have a .json file extension.
            if (!".json".Equals(Path.GetExtension(file), StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            // Config files must not have the reservered names
            var fileName = Path.GetFileNameWithoutExtension(file);
            foreach (var reservedName in _reservedConfigFileNames)
            {
                if (reservedName.Equals(fileName, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }

            // Config files must not contain whitespaces or characters in the forbiddenChars list.
            return Path.GetFileNameWithoutExtension(file)
                .Any(c => char.IsWhiteSpace(c) || _forbiddenChars.Contains(c));
        }

19 Source : TextureAtlasSamplerFactory.cs
with GNU Lesser General Public License v2.1
from axiom3d

public bool AddTextureAtlasDefinition(StreamReader stream, List<TextureAtlasRecord> textureAtlasTable)
        {
            var tmpMap = new Dictionary<string, List<TextureAtlasRecord>>();
            bool isSuccess = false;
            while (stream.EndOfStream == false)
            {
                string line = stream.ReadLine();
                int indexWithNotWhiteSpace = -1;
                for (int i = 0; i < line.Length; i++)
                {
                    char cur = line[i];
                    if (char.IsWhiteSpace(cur) == false)
                    {
                        indexWithNotWhiteSpace = i;
                        break;
                    }
                }
                //check if this is a line with information
                if (indexWithNotWhiteSpace != -1 && line[indexWithNotWhiteSpace] != '#')
                {
                    //parse the line
                    var strings = line.Split(new string[]
                                              {
                                                  ",\t"
                                              }, StringSplitOptions.None);

                    if (strings.Length > 8)
                    {
                        string textureName = strings[1];

                        if (tmpMap.ContainsKey(textureName) == false)
                        {
                            tmpMap.Add(textureName, new List<TextureAtlasRecord>());
                        }

                        //file line format: <original texture filename>/t/t<atlas filename>, <atlas idx>, <atlas type>, <woffset>, <hoffset>, <depth offset>, <width>, <height>
                        //                                                       1                  2            3           4         5             6           7         8
                        var newRecord = new TextureAtlasRecord(strings[0], strings[1], float.Parse(strings[4]),
                                                                float.Parse(strings[5]), float.Parse(strings[7]),
                                                                float.Parse(strings[8]), tmpMap[textureName].Count);

                        tmpMap[textureName].Add(newRecord);
                        if (textureAtlasTable != null)
                        {
                            textureAtlasTable.Add(newRecord);
                        }
                        isSuccess = true;
                    }
                }
            }
            //place the information in the main texture
            int maxTextureCount = 0;

            foreach (var key in tmpMap.Keys)
            {
                SetTextureAtlasTable(key, tmpMap[key]);
                if (maxTextureCount >= tmpMap[key].Count)
                {
                    maxTextureCount = tmpMap[key].Count;
                }

                if (maxTextureCount > TextureAtlreplacedampler.MaxSafeAtlasedTextuers)
                {
                    Axiom.Core.LogManager.Instance.Write(
                        "Warning : atlas texture has too many internally defined textures. Shader may fail to compile.");
                }
            }

            return isSuccess;
        }

19 Source : GLSLESPreprocessor.cs
with GNU Lesser General Public License v2.1
from axiom3d

public bool GetValue( out long value )
			{
				value = 0;

				long val = 0;
				int i = 0;

				while ( Char.IsWhiteSpace( this.String[ i ] ) )
				{
					i++;
				}

				long baseVal = 10;
				if ( this.String[ i ] == '0' )
				{
					if ( ( this.Length > i + 1 ) && this.String[ i + 1 ] == 'x' )
					{
						baseVal = 16;
						i += 2;
					}
					else
					{
						baseVal = 8;
					}
				}

				for ( ; i < this.Length; i++ )
				{
					char c = this.String[ i ];
					if ( Char.IsWhiteSpace( c ) )
					{
						break;
					}

					if ( c >= 'a' && c <= 'z' )
					{
						c -= (char) ( 'a' - 'A' );
					}

					c -= '0';
					if ( c < 0 )
					{
						return false;
					}

					if ( c > 9 )
					{
						c -= (char) ( 'A' - '9' - 1 );
					}
					if ( c >= baseVal )
					{
						return false;
					}

					val = ( val * baseVal ) + c;
				}
				//Check that all other characters are just spaces
				for ( ; i < this.Length; i++ )
				{
					if ( !Char.IsWhiteSpace( this.String[ i ] ) )
					{
						return false;
					}
				}

				value = val;
				return true;
			}

19 Source : GLSLESPreprocessor.cs
with GNU Lesser General Public License v2.1
from axiom3d

public Token GetToken( bool expand )
		{
			int index = 0;
			char c = this.Source[ index ];
			if ( c == '\n' || this.Source == System.Environment.NewLine )
			{
				this.Line++;
				this.BOL = true;
				if ( c == '\r' )
				{
					index++;
				}
				return new Token( Token.Kind.Newline, this.Source, this.Source.Length - index );
			}
			else if ( Char.IsWhiteSpace( c ) )
			{
				while ( index < this.Source.Length && this.Source[ index ] != '\r' && this.Source[ index ] != '\n' && Char.IsWhiteSpace( this.Source[ index ] ) )
				{
					index++;
				}

				return new Token( Token.Kind.Whitespace, this.Source, index );
			}
			else if ( Char.IsDigit( c ) )
			{
				this.BOL = false;
				if ( c == '0' && this.Source[ 1 ] == 'x' ) //hex numbers
				{
					index++;
					while ( index < this.Source.Length && char.IsNumber( this.Source[ index ] ) )
					{
						index++;
					}
				}
				else
				{
					while ( index < this.Source.Length && Char.IsDigit( this.Source[ index ] ) )
					{
						index++;
					}
				}

				return new Token( Token.Kind.Number, this.Source, index );
			}
			else if ( c == '_' || Char.IsLetterOrDigit( c ) )
			{
				this.BOL = false;

				while ( index < this.Source.Length && ( this.Source[ index ] == '_' || Char.IsLetterOrDigit( this.Source[ index ] ) ) )
				{
					index++;
				}

				return new Token( Token.Kind.Number, this.Source, index );
			}
			else if ( c == '"' || c == '\'' )
			{
				this.BOL = false;
				while ( index < this.Source.Length && this.Source[ index ] != c )
				{
					if ( this.Source[ index ] == '\\' )
					{
						index++;
						if ( index >= this.Source.Length )
						{
							break;
						}
					}
					if ( this.Source[ index ] == '\n' )
					{
						this.Line++;
					}
					index++;
				}
				if ( index < this.Source.Length )
				{
					index++;
				}
				return new Token( Token.Kind.String, this.Source, index );
			}
			else if ( c == '/' && this.Source[ index ] == '/' )
			{
				this.BOL = false;
				index++;
				while ( index < this.Source.Length && this.Source[ index ] != '\r' && this.Source[ index ] != '\n' )
				{
					return new Token( Token.Kind.Linecomment, this.Source, index );
				}
			}
			else if ( c == '/' && this.Source[ index ] == '*' )
			{
				this.BOL = false;
				index++;

				while ( index < this.Source.Length && ( this.Source[ 0 ] != '*' || this.Source[ 1 ] != '/' ) )
				{
					if ( this.Source[ index ] == '\n' )
					{
						this.Line++;
					}
					index++;
				}
				if ( index < this.Source.Length && this.Source[ index ] == '*' )
				{
					index++;
				}
				if ( index < this.Source.Length && this.Source[ index ] == '/' )
				{
					index++;
				}
				return new Token( Token.Kind.Comment, this.Source, index );
			}
			else if ( c == '#' && this.BOL )
			{
				//Skip all whitespaces after '#'
				while ( index < this.Source.Length && Char.IsWhiteSpace( this.Source[ index ] ) )
				{
					index++;
				}
				while ( index < this.Source.Length && !char.IsWhiteSpace( this.Source[ index ] ) )
				{
					index++;
				}
				return new Token( Token.Kind.Directive, this.Source, index );
			}
			else if ( c == '\\' && index < this.Source.Length && ( this.Source[ index ] == '\r' || this.Source[ index ] == '\n' ) )
			{
				//Treat backslash-newline as a whole token
				if ( this.Source[ index ] == '\r' )
				{
					index++;
				}
				if ( this.Source[ index ] == '\n' )
				{
					index++;
				}
				this.Line++;
				this.BOL = true;
				return new Token( Token.Kind.Linecont, this.Source, index );
			}
			else
			{
				this.BOL = false;
				//Handle double-char operators here

				if ( c == '>' && this.Source[ index ] == '>' || this.Source[ index ] == '=' )
				{
					index++;
				}
				else if ( c == '<' && this.Source[ index ] == '<' || this.Source[ index ] == '=' )
				{
					index++;
				}
				else if ( c == '!' && this.Source[ index ] == '=' )
				{
					index++;
				}
				else if ( c == '=' && this.Source[ index ] == '=' )
				{
					index++;
				}
				else if ( ( c == '|' || c == '&' || c == '^' ) && this.Source[ index ] == c )
				{
					index++;
				}

				return new Token( Token.Kind.Punctuation, this.Source, index );
			}

			return Token.Error;
		}

19 Source : GLSLESPreprocessor.cs
with GNU Lesser General Public License v2.1
from axiom3d

public Token HandleDirective( Token token, int line )
		{
			//replacedzye preprocessor directive
			char directive = token.String[ 1 ];
			int dirlength = token.Length - 1;
			while ( dirlength > 0 && Char.IsWhiteSpace( directive ) )
			{
				dirlength--;
				directive++;
			}

			int old_line = this.Line;

			//collect the remaining part of the directive until EOL
			Token t, last = null;
			bool done = false;
			do
			{
				t = this.GetToken( false );
				if ( t.Type == Token.Kind.Newline )
				{
					//No directive arguments
					last = t;
					t.Length = 0;
					done = true;
					break;
				}
			} while ( t.Type == Token.Kind.Whitespace || t.Type == Token.Kind.Linecont || t.Type == Token.Kind.Comment || t.Type == Token.Kind.Linecomment );
			if ( !done )
			{
				for ( ;; )
				{
					last = this.GetToken( false );
					switch ( last.Type )
					{
						case Token.Kind.EOS:
							//Can happen and is not an error
							done = true;
							break;
						case Token.Kind.Linecomment:
						case Token.Kind.Comment:
							//Skip comments in macros
							continue;
						case Token.Kind.Error:
							return last;
						case Token.Kind.Linecont:
							continue;
						case Token.Kind.Newline:
							done = true;
							break;

						default:
							break;
					}


					if ( done )
					{
						break;
					}
					else
					{
						t.Append( last );
						t.Type = Token.Kind.Text;
					}
				}
			}
			if ( done )
			{
				this.EnableOutput = false;
				bool outputEnabled = this.EnableOutput;
				bool rc;
				if ( outputEnabled )
				{
					string dir = token.String;

					if ( dir.Contains( "define" ) )
					{
						rc = this.HandleDefine( t, line );
					}
					else if ( dir.Contains( "undef" ) )
					{
						rc = this.HandleUnDef( t, line );
					}
					else if ( dir.Contains( "ifdef" ) )
					{
						rc = this.HandleIfDef( t, line );
					}
					else if ( dir.Contains( "ifndef" ) )
					{
						rc = this.HandleIfDef( t, line );
						if ( rc )
						{
							this.EnableOutput = true;
						}
					}
					else if ( dir.Contains( "if" ) )
					{
						rc = this.HandleIf( t, line );
					}
					else if ( dir.Contains( "else" ) )
					{
						rc = this.HandleElse( t, line );
					}
					else if ( dir.Contains( "endif" ) )
					{
						rc = this.HandleEndIf( t, line );
					}
					else
					{
						//Unknown preprocessor directive, roll back and preplaced through
						this.Line = old_line;
						this.Source = token.String + token.Length;
						token.Type = Token.Kind.Text;
						return token;
					}

					if ( !rc )
					{
						return new Token( Token.Kind.Error );
					}

					return last;
				}
			}

			//To make compiler happy
			return Token.Error;
		}

19 Source : MathConverter.cs
with MIT License
from ay2015

private void SkipWhiteSpace()
            {
                while (pos < text.Length && Char.IsWhiteSpace((text[pos]))) ++pos;
            }

19 Source : StringExtensions.cs
with GNU General Public License v3.0
from az64

private static bool HasWidth(char c)
        {
            return !char.IsWhiteSpace(c) && !specialCharacters.Contains(c);
        }

19 Source : CSVParser.cs
with MIT License
from azist

private static IEnumerable<string> parseCSVRow(CharIteratorWithStats enumerator, bool trim, bool skipIfMore, bool addIfLess, StringBuilder sb, StringBuilder ws)
    {
      if (sb.Length != 0)
        throw new CSVParserException("{0}.ParseCSVRow(!sb.empty)".Args(enumerator.GetType().Name), enumerator.Line, enumerator.Column);
      if (ws.Length != 0)
        throw new CSVParserException("{0}.ParseCSVRow(!ws.empty)".Args(enumerator.GetType().Name), enumerator.Line, enumerator.Column);
      var state = State.None;
      enumerator.Count = 0;
      while(enumerator.MoveNext())
      {
        var c = enumerator.Current;
        if (('\n' == c || '\r' == c) && state != State.Quote)
        {
          if ('\r' == c && enumerator.HasNext && '\n' == enumerator.Next)
            enumerator.MoveNext();
          break;
        }

        if (char.IsWhiteSpace(c))
        {
          ws.Append(c);
          continue;
        }
        switch (state)
        {
          case State.None:
            if ('"' == c && (ws.Length == 0 || trim))
            {
              state = State.Quote;
              ws.Clear();
            }
            else if (',' == c)
            {
              if (!trim) sb.Append(ws.ToString());
              ws.Clear();
              if (!(skipIfMore && enumerator.RequiredCount >= 0 && enumerator.Count >= enumerator.RequiredCount))
              {
                enumerator.Count++;
                yield return sb.ToString();
              }
              sb.Clear();
            }
            else
            {
              state = State.Value;
              if (!trim) sb.Append(ws.ToString());
              ws.Clear();
              sb.Append(c);
            }
            break;
          case State.Value:
            if (',' == c)
            {
              state = State.None;
              if (!trim) sb.Append(ws.ToString());
              ws.Clear();
              if (!(skipIfMore && enumerator.RequiredCount >= 0 && enumerator.Count >= enumerator.RequiredCount))
              {
                enumerator.Count++;
                yield return sb.ToString();
              }
              sb.Clear();
            }
            else
            {
              sb.Append(ws.ToString());
              ws.Clear();
              sb.Append(c);
            }
            break;
          case State.Quote:
            if ('"' == c)
            {
              sb.Append(ws.ToString());
              ws.Clear();
              if (enumerator.HasNext && '"' == enumerator.Next)
              {
                sb.Append(c);
                enumerator.MoveNext();
              }
              else
                state = State.AfterQuote;
            }
            else
            {
              sb.Append(ws.ToString());
              ws.Clear();
              sb.Append(c);
            }
            break;
          case State.AfterQuote:
            if (',' == c)
            {
              state = State.None;
              if (!trim) sb.Append(ws.ToString());
              ws.Clear();
              if (!(skipIfMore && enumerator.RequiredCount >= 0 && enumerator.Count >= enumerator.RequiredCount))
              {
                enumerator.Count++;
                yield return sb.ToString();
              }
              sb.Clear();
            }
            else
              throw new CSVParserException("{0}.parseCSVRow()".Args(enumerator.GetType().Name), enumerator.Line, enumerator.Column);
            break;
        }
      }

      if (!trim && state != State.AfterQuote) sb.Append(ws.ToString());
      else if (!trim && state == State.AfterQuote && ws.Length != 0)
        throw new CSVParserException("{0}.ParseCSVRow()".Args(enumerator.GetType().Name), enumerator.Line, enumerator.Column);
      ws.Clear();
      if (!(skipIfMore && enumerator.RequiredCount >= 0 && enumerator.Count >= enumerator.RequiredCount))
      {
        enumerator.Count++;
        yield return sb.ToString();
      }
      if (addIfLess && enumerator.RequiredCount >= 0)
        for (; enumerator.Count < enumerator.RequiredCount; enumerator.Count++)
          yield return string.Empty;
      if (enumerator.RequiredCount >= 0 && enumerator.Count != enumerator.RequiredCount)
        throw new CSVParserException("{0}.parseCSVRow(Count!=RequiredCount)({1}!={2})".Args(enumerator.GetType().Name, enumerator.Count, enumerator.RequiredCount), enumerator.Line, enumerator.Column);
      if (enumerator.RequiredCount < 0 && enumerator.DetectCount)
        enumerator.RequiredCount = enumerator.Count;
      sb.Clear();
    }

19 Source : DataEntryUtils.cs
with MIT License
from azist

public static bool CheckTelephone(string phone)
    {
      if (String.IsNullOrEmpty(phone)) return false;
      if (phone.Length < 7) return false;

      char c;
      var hasFirstParenthesis = false;
      var hreplacedecondParenthesis = false;
      var prevIsSpecial = false;
      var area = false;
      var inParentheses = false;
      for (int i = 0; i < phone.Length; i++)
      {
        c = phone[i];
        if (i == 0)
        {
          if (Char.IsWhiteSpace(c)) return false;
          if (c == '+')
          {
            prevIsSpecial = true;
            continue;
          }
          else
            area = true;
        }
        if (i == (phone.Length - 1) && !IsLatinLetterOrDigit(c)) return false;


        if (c == '(')
        {
          if (hasFirstParenthesis || hreplacedecondParenthesis || prevIsSpecial) return false;
          hasFirstParenthesis = true;
          inParentheses = true;
          continue;
        }

        if (c == ')')
        {
          if (hreplacedecondParenthesis || prevIsSpecial) return false;
          hreplacedecondParenthesis = true;
          prevIsSpecial = true;
          inParentheses = false;
          continue;
        }

        if (c == '-' || c == '.')
        {
          if (prevIsSpecial || inParentheses) return false;
          prevIsSpecial = true;
          continue;
        }

        if (c == ' ')
        {
          if ((prevIsSpecial && phone[i - 1] != ')') || inParentheses) return false;
          prevIsSpecial = true;
          continue;
        }

        if (area)
        {
          for (int j = 0; j < 3 && i < phone.Length - 2; j++)
          {
            c = phone[i + j];
            if (!Char.IsDigit(c)) return false;
          }
          if (inParentheses && phone[i + 3] != ')') return false;
          area = false;
          i = i + 2;
          continue;
        }

        if (!IsLatinLetterOrDigit(c)) return false;
        prevIsSpecial = false;
      }
      if (inParentheses || (hreplacedecondParenthesis && !hasFirstParenthesis))
        return false;

      return true;
    }

19 Source : SkyExtensions.cs
with MIT License
from azist

public static bool IsValidName(this string name)
    {
      if (name==null) return false;

      var started = false;
      var ws = false;

        for(var i=0; i<name.Length; i++)
        {
          var c = name[i];
          ws = Char.IsWhiteSpace(c);
          if (!started && ws) return false;//no leading whitespace
          if (!ws) started = true;
          if (SysConsts.NAME_INVALID_CHARS.Contains(c)) return false;
        }

      if (!started || ws) return false;//trailing whitespace

      return true;
    }

19 Source : Lexer.cs
with Apache License 2.0
from azizamari

public SyntaxToken Lex()
        {
            //numeric

            //operators
            //<ws>

            _start = _position;
            _kind = SyntaxKind.BadToken;
            _value = null;


            switch (Current)
            {
                case '\0':
                    _kind=SyntaxKind.EndOfFileToken;
                    break;
                case '+':
                    _kind = SyntaxKind.PlusToken;
                    _position++;
                    break;
                case '-':
                    _kind = SyntaxKind.MinusToken;
                    _position++;
                    break;
                case '%':
                    _kind = SyntaxKind.ModuloToken;
                    _position++;
                    break;
                case '(':
                    _kind = SyntaxKind.OpenParenthesisToken;
                    _position++;
                    break;
                case ')':
                    _kind = SyntaxKind.ClosedParenthesisToken;
                    _position++;
                    break;
                case '[':
                    _kind = SyntaxKind.OpenBracketToken;
                    _position++;
                    break;
                case ']':
                    _kind = SyntaxKind.ClosedBracketToken;
                    _position++;
                    break;
                case '{':
                    _kind = SyntaxKind.OpenBraceToken;
                    _position++;
                    break;
                case '}':
                    _kind = SyntaxKind.ClosedBraceToken;
                    _position++;
                    break;
                case '~':
                    _kind = SyntaxKind.TildeToken;
                    _position++;
                    break;
                case '^':
                    _kind = SyntaxKind.HatToken;
                    _position++;
                    break;
                case ',':
                    _kind = SyntaxKind.CommaToken;
                    _position++;
                    break;
                case ':':
                    _kind = SyntaxKind.ColonToken;
                    _position++;
                    break;
                case '/':
                    _position++;
                    if (Current != '/')
                    {
                        _kind = SyntaxKind.SlashToken;
                    }
                    else
                    {
                        _kind = SyntaxKind.SlashSlashToken;
                        _position++;
                    }
                    break;
                case '*':
                    _position++;
                    if (Current != '*')
                    {
                        _kind = SyntaxKind.StarToken;
                    }
                    else
                    {
                        _kind = SyntaxKind.StarStarToken;
                        _position++;
                    }
                    break;
                case '&':
                    _position++;
                    if (Current != '&')
                    {
                        _kind = SyntaxKind.AmpersandToken;
                    }
                    else
                    {
                        _kind = SyntaxKind.AmpersandAmpersandToken;
                        _position++;
                    }
                    break;
                case '|':
                    _position++;
                    if (Current != '|')
                    {
                        _kind = SyntaxKind.PipeToken;
                    }
                    else
                    {
                        _kind = SyntaxKind.PipePipeToken;
                        _position++;
                    }
                    break;
                case '=':
                    _position++;
                    if (Current != '=')
                    {
                        _kind = SyntaxKind.EqualsToken;
                    }
                    else
                    {
                        _kind = SyntaxKind.EqualsEqualsToken;
                        _position++;
                    }
                    break;
                case '!':
                    _position++;
                    if (Current != '=')
                    {
                        _kind = SyntaxKind.BangToken;
                    }
                    else
                    {
                        _kind = SyntaxKind.BangEqualsToken;
                        _position++;
                    }
                    break;
                case '>':
                    _position++;
                    if (Current != '=')
                    {
                        _kind = SyntaxKind.GreaterToken;
                    }
                    else
                    {
                        _kind = SyntaxKind.GreaterOrEqualsToken;
                        _position++;
                    }
                    break;
                case '<':
                    _position++;
                    if (Current != '=')
                    {
                        _kind = SyntaxKind.LessToken;
                    }
                    else
                    {
                        _kind = SyntaxKind.LessOrEqualsToken;
                        _position++;
                    }
                    break;
                case '"':
                    ReadString();
                    break;
                case '0': case '1':case '2':case '3':case '4':
                case '5': case '6':case '7':case '8':case '9':
                    ReadNumberToken();
                    break;
                case ' ':
                case '\t':
                case '\r':
                case '\n':
                    ReadWhiteSpace();
                    break;
                default:
                    if (char.IsLetter(Current))
                    {
                        ReadIdentifierOrKeyword();

                    }
                    else if (char.IsWhiteSpace(Current))
                    {
                        ReadWhiteSpace();
                    }
                    else
                    {
                        var span = new TextSpan(_position, 1);
                        var location = new TextLocation(_text, span);
                        _diagnostics.ReportBadCharacter(location,Current);
                        _position += 1;
                    }
                    break;

            }
            var length = _position - _start;
            var text = _text.ToString(_start,length);
            if (text == null)
            {
                text = _text.ToString(_start, length);
            }
            return new SyntaxToken(_syntaxTree, _kind, _start, text, _value);
        }

19 Source : Lexer.cs
with Apache License 2.0
from azizamari

private void ReadWhiteSpace()
        {
            while (char.IsWhiteSpace(Current))
                _position++;

            _kind = SyntaxKind.WhiteSpaceToken;
        }

19 Source : StringReader.cs
with Apache License 2.0
from Azure-App-Service

public string ReadUntilWhitespace()
        {
            return ReadUntil(ch => Char.IsWhiteSpace(ch));
        }

19 Source : StringReader.cs
with Apache License 2.0
from Azure-App-Service

public void SkipWhitespace()
        {
            ReadUntil(ch => !Char.IsWhiteSpace(ch));
        }

19 Source : StringExtension.cs
with MIT License
from baiyunchen

public static bool IsNullOrWhiteSpace(this string value)
        {
            if (value == null) return true;

            for (int i = 0; i < value.Length; i++)
            {
                if (!Char.IsWhiteSpace(value[i])) return false;
            }

            return true;
        }

19 Source : StringExtensions.cs
with The Unlicense
from BAndysc

public static string ToAlphanumerical(this string str)
        {
            char[] arr = str.Where(c => (char.IsLetterOrDigit(c) || 
                                         char.IsWhiteSpace(c) || 
                                         c == '-')).ToArray(); 

            return new string(arr);
        }

19 Source : CardHelper.cs
with MIT License
from banksystembg

private string CreateCheckDigit(string number)
        {
            var digitsSum = number
                .ToCharArray()
                .Where(c => !char.IsWhiteSpace(c))
                .ToArray()
                .Reverse()
                .Select(CharToInt)
                .Select((digit, index) => this.isEven(index) ? this.doubleDigit(digit) : digit)
                .Sum();

            digitsSum *= 9;

            return digitsSum
                .ToString()
                .ToCharArray()
                .Last()
                .ToString();
        }

19 Source : CardHelper.cs
with MIT License
from banksystembg

public bool CheckLuhn(string creditCardNumber)
        {
            var checkSum = creditCardNumber
                .ToCharArray()
                .Where(c => !char.IsWhiteSpace(c))
                .ToArray()
                .Select(CharToInt)
                .Reverse()
                .Select((digit, index) => this.isEven(index + 1) ? this.doubleDigit(digit) : digit)
                .Sum();

            return checkSum % 10 == 0;
        }

See More Examples