正在检测文本框中的空白

本文关键字:空白 文本 检测 | 更新日期: 2023-09-27 18:20:14

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

正在检测文本框中的空白

使用IndexOf

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

这个函数应该能帮你完成任务。

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;
}

不太清楚问题是什么,但如果你只想知道给定字符串中的任何地方是否有空白,那么与其他堆栈用户提出的解决方案(同样有效)不同的解决方案是:

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;
        }
    }
}

如果您想要的是确定是否出现给定的连续空格序列,那么您将需要在regex模式字符串中添加更多空格。提到http://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx。