c# - 如何确保字符串中的任何位置不超过一个空格?

标签 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(" ", "");

但这仅适用于我确定字符串中包含单个空格,这就是为什么我需要确保字符串永远不会有更多空格,以便我可以使用该替换。

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

最佳答案

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

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

关于c# - 如何确保字符串中的任何位置不超过一个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56845167/

相关文章:

c# - 将 JSON 作为 .json 文件返回

c# - sql c# 删除 div id 的语法

python - f 字符串格式是否将变量转换为字符串?

python - Pandas DF : Create New Col by removing last word from of existing column

php - 无法从 PHP 中的字符串中删除所有换行符

html - 在单词之间的空白处换行后更改字体大小

c# - 用于查找基于 HSL 的颜色是否接近另一种颜色的 bool 函数

c# - 是否有将 IEnumerator 转换为 IEnumerable 的内置方法

c++ - 清理多个 if 语句 C++

Python:生成多个带空格的字符串组合