Matt Douhan
Matt Douhan

Reputation: 2113

How can I ensure a string has no more than a single whitespace anywhere in it?

I am taking a string as an input and due to some processing later on it is critical that the string does not contain 2 or more consecutive whitepaces anywhere in the string.

For example

string foo = "I am OK" is a valid string
string foo = " I am OK " is a valid string
string foo = "  I am OK" is NOT a valid string due to the initial double white space
string foo = "I am OK  " is NOT a valid string due to the trailing double whitespaces
string foo = " I am  OK " is NOT a valid string since it has 2 whitespaces between am and OK

I think you get the picture, I tried to normalize the string using the following code

string normalizedQuery = apiInputObject.Query.Replace(" ", "");

But this only works I am sure the string has single whitespaces in it, thats why I need to ensure the string never has more so I can use that replace.

How can I make sure the string fits my format?

Upvotes: 2

Views: 342

Answers (5)

shubham
shubham

Reputation: 801

Based on your requirement, I think you just need to replace two consecutive white-spaces to one.

foo=foo.Replace("  "," ");

As pointed by Gian, "Repeat until no double space is in the string".

Upvotes: 1

bvsh
bvsh

Reputation: 64

I would loop through the entire string, character by character and check if two side by side characters are whitespace:

for(int i=0; i<foo.Length-1; i++){
    if(foo[i] == ' ' && foo[i+1] == ' '){
        return false;
    }
}
return true;

Upvotes: 0

John Wu
John Wu

Reputation: 52250

Use IndexOf.

public static void Main()
{
    var tests = new string[]
    {
         "I am OK",
         " I am OK ",
         "  I am OK",
         "I am OK  ",
         " I am  OK " 
    };
    foreach (var test in tests)
    {
        var hasDoubleSpace = (test.IndexOf("  ") != -1);
        Console.WriteLine("'{0}' {1} double spaces", test, hasDoubleSpace ? "has" : "does not have");
    }
}

Output:

'I am OK' does not have double spaces
' I am OK ' does not have double spaces
'  I am OK' has double spaces
'I am OK  ' has double spaces
' I am  OK ' has double spaces

Fiddle

Upvotes: 2

Eugene Ryabtsev
Eugene Ryabtsev

Reputation: 2301

You can use String.Contains to look for " ", but if the user can type ANYTHING, you have a bigger problem than simple spaces, like various unicode spaces, hieroglyphs et cetera (that is, unless your post-processing only looks for simple spaces and is otherwise unicode-tolerant).

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521409

You may try using the regex pattern @"^(?!.*[ ]{2}).*$":

Match result = Regex.Match("One space", @"^(?!.*[ ]{2}).*$");
if (result.Success) {
    Console.WriteLine("ONLY ONE SPACE OR LESS");
}

Upvotes: 3

Related Questions