This is what I have:
if (userVar == " ")
{
Console.WriteLine("stop");
}
OK but that only handles it for one spacing. What if the user presses 2 spaces, 3 spaces, 100 spaces in the console, how do I make an if statement for all of those?
This is what I have:
if (userVar == " ")
{
Console.WriteLine("stop");
}
OK but that only handles it for one spacing. What if the user presses 2 spaces, 3 spaces, 100 spaces in the console, how do I make an if statement for all of those?
What you need is IsNullOrWhiteSpace function https://learn.microsoft.com/en-us/dotnet/api/system.string.isnullorwhitespace?view=netframework-4.7.2
In order to check if every character in the string is a space, you could do the following:
if(userVar.All(x => x == " "))
{
Console.WriteLine("stop");
}
Alternatively, if you don't want to use lambdas, you could do this relatively easily with a function:
public static boolean IsAllSpaces(string input)
{
if(input == null || input == String.Empty)
{
return false;
}
foreach(char c in input)
{
if(c != " ")
{
return false;
}
}
return true;
}
Note that the first will throw an exception if the string is null, while the second will return false. Up to you which is preferable behavior, you could check for null in the first example before calling All
if you want.
if (userVar.length > 0 && String.IsNullOrEmpty(userVar.Trim())
{
Console.WriteLine("stop");
}
It has caracters and they are only spaces...
Use it like this:
if (String.IsNullOrWhiteSpace(userVar))
{
Console.WriteLine("stop");
}
According to documentation: Returns true if the value parameter is null or Empty, or if value consists exclusively of white-space characters.
Well, if you want NOT A SINGLE space. you can use string.Conatins()
function.
if (userVar.Contains(" "))
{
Console.WriteLine("stop");
}
NOTE: No matter user inputs 1 space
or 100, it'll detect.