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?
use IndexOf
if( "1 1a".IndexOf(' ') >= 0 ) {
// there is a space.
}
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.
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;
}