简体   繁体   English

在文本框中检测空白

[英]Detecting whitespace in textbox

在具有多个空格(例如1 1 A)的WinForms文本框中,在1s之间有空格的情况下,如何通过字符串方法或正则表达式检测到该空格?

use IndexOf 使用IndexOf

if( "1 1a".IndexOf(' ') >= 0 ) {
    // there is a space.
}

This function should do the trick for you. 此功能将为您解决问题。

bool DoesContainsWhitespace()
{
   return textbox1.Text.Contains(" ");
}
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;
}

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. 有关选项,请参考http://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM