如何确保字符串中的任何地方都不能超过单个空格?

时间:2019-07-02 04:05:13

标签: c# string whitespace removing-whitespace

我将字符串作为输入,由于稍后需要进行一些处理,因此该字符串在字符串中的任何位置都不包含2个或多个连续的白点至关重要。

例如

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

我想您明白了,我尝试使用以下代码对字符串进行规范化

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

但这只能奏效,我确定字符串中包含单个空格,这就是为什么我需要确保字符串再也没有空格,所以我可以使用该替换。

如何确保字符串适合我的格式?

6 个答案:

答案 0 :(得分:3)

您可以尝试使用正则表达式模式@"^(?!.*[ ]{2}).*$"

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

答案 1 :(得分:2)

使用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");
    }
}

输出:

'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

答案 2 :(得分:1)

根据您的要求,我认为您只需要将两个连续的空格替换为一个即可。

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

答案 3 :(得分:0)

您可以使用String.Contains查找" ",但是如果用户可以键入ANYTHING,则比简单的空格(例如各种unicode空格,象形文字等)要面临更大的问题(也就是说,除非您的后期处理只会寻找简单的空格,否则会被unicode容忍)。

答案 4 :(得分:0)

function httpPostRequest($url, $strRequest,$auth)
    {

    $fields = array(
        'strRequest' => $strRequest,
        'access_token' => $access_token
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $isSecure = strpos($url, "https://");
    if ($isSecure === 0) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    }

    $result = curl_exec($ch);
    $this->errorCode = curl_errno($ch);
    $this->errorMessage = curl_error($ch);
    return $result;
    }

答案 5 :(得分:0)

我将逐个字符遍历整个字符串,并检查两个并排字符是否为空格:

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