【问题标题】:Allow only one space between words in c#c#中单词之间只允许一个空格
【发布时间】:2016-01-20 10:43:33
【问题描述】:

我想在 Windows 窗体中进行验证,以便在文本值之间只允许一个空格。在c#中怎么做。提前致谢。 我不想仅在 c# 中使用任何其他方法进行此验证。请帮我做这件事。

if (e.Handled = (e.KeyChar == (char)Keys.Space)) 
    { 
    MessageBox.Show("Spaces are not allowed at start"); 
    } 
}

【问题讨论】:

  • if (string.Join(" ", test.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries)) != test) ... // bad spacing
  • 请考虑将其中一个答案标记为已接受。

标签: c# winforms


【解决方案1】:
string str = "words   with multiple         spaces";

Regex regex = new Regex(@"[ ]{2,}", RegexOptions.None);     
str = regex.Replace(str, @" "); // "words with multiple spaces"

【讨论】:

    【解决方案2】:

    获取您的字符串长度,然后测试每个字符是否为空格。如果它有超过 1 个空格,则使您的函数失败。

    String myString = "My String";
    int myStringLength = myString.length;
    int nrOfSpaces = 0;
    
    for(i = 0; i <= myStringLength)
    {
       if(myString[i] == " ")
       {
          nrofspaces++;
          i++;
       }
    }
    

    【讨论】:

    • 这只适用于两个词...如果输入有 3 个词怎么办?然后有(正确)两个空格。
    • 不,它计算字符串中的所有空格。
    猜你喜欢
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    相关资源
    最近更新 更多