Detecting whitespace in textbox

后端 未结 4 996
无人及你
无人及你 2021-01-16 23:01

In a WinForms textbox with multiple whitespaces (e.g. 1 1 A), where, between the 1s, there is whitespace, how could I detect this via the string methods or regex?

相关标签:
4条回答
  • 2021-01-16 23:25

    use IndexOf

    if( "1 1a".IndexOf(' ') >= 0 ) {
        // there is a space.
    }
    
    0 讨论(0)
  • 2021-01-16 23:40

    Not pretty clear what the problem is, but in case you just want a way to tell if there is a white space anywhere in a given string, a different solution to the ones proposed by the other stack users (which also work) is:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    
    namespace Testing
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(PatternFound("1 1 a"));
                Console.WriteLine(PatternFound("1     1    a"));
                Console.WriteLine(PatternFound("            1     1   a"));
    
            }
    
            static bool PatternFound(string str)
            {
                Regex regEx = new Regex("\\s");
                Match match = regEx.Match(str);
                return match.Success;
            }
        }
    }
    

    in case what you want is determining whether a given succession of consecutive white spaces appear, then you will need to add more to the regex pattern string. Refer to http://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx for the options.

    0 讨论(0)
  • 2021-01-16 23:47

    This function should do the trick for you.

    bool DoesContainsWhitespace()
    {
       return textbox1.Text.Contains(" ");
    }
    
    0 讨论(0)
  • 2021-01-16 23:47
    int NumberOfWhiteSpaceOccurances(string textFromTextBox){
     char[] textHolder = textFromTextBox.toCharArray();
     int numberOfWhiteSpaceOccurances = 0;
     for(int index= 0; index < textHolder.length; index++){
       if(textHolder[index] == ' ')numberOfWhiteSpaceOccurances++;
     }
     return numberOfWhiteSpaceOccurances;
    }
    
    0 讨论(0)
提交回复
热议问题