【问题标题】:How to add a space after 3rd character in a text box if length is 6 characters long or after 4th character if 7 characters long如果长度为 6 个字符,如何在文本框中的第 3 个字符后添加空格,如果长度为 7 个字符,如何在第 4 个字符后添加空格
【发布时间】:2019-04-09 10:11:02
【问题描述】:

我正在尝试在文本框中的第 3 个或第 4 个字符之后添加一个空格,具体取决于总字符数。

例如,如果文本框值包含 6 个字符,则在第 3 个字符后添加一个空格。如果文本框值包含 7 个字符,则在第 4 个字符后添加一个空格。

文本框中 7 个字符的示例

文本框中 6 个字符的示例

我目前正试图让它发挥作用。

private void FirstPostcode_LostFocus(object sender, RoutedEventArgs e)
    {
        if (FirstPostcode.Text.Length == 3)
        {
            FirstPostcode.Text += " ";
        }
    }

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 您的代码似乎是为TextChanged 事件设计的。键入时,将在 3 个字符后添加一次空格。对于LostFocus 或输入按键,您必须插入空格。你可以改用masked textbox。
  • 为什么要检查字符串的长度是否为3,当您在问题中询问长度6 和7 时?
  • 你最好在离开盒子时格式化邮政编码,你打算对像“B1 1AA”这样的邮政编码做什么?因为一个常数是最后 3 位数字。
  • 你想在mvvm做吗?
  • @BugFinder 我没有注意到它是 3,我将它用于物理属性,所以我永远不会使用像“B1 1AA”这样的邮政编码。

标签: c# wpf windows


【解决方案1】:

您可以使用Insert() 在右数第三个位置插入一个空格。

if (FirstPostcode.Text >= 3)
{
    FirstPostcode.Text = FirstPostcode.Text.Insert(FirstPostcode.Text.Length - 3, " ");
}

如果您想先检查空格是否已插入并且不想再次插入,您可以在字符串上使用索引器。

if (FirstPostcode.Text.Length == 3 
     || FirstPostcode.Text.Length >= 4
        && FirstPostcode.Text[FirstPostcode.Text.Length - 4] != ' ')
{
    FirstPostcode.Text = FirstPostcode.Text.Insert(FirstPostcode.Text.Length - 3, " ");
}

【讨论】:

    【解决方案2】:

    尝试以下:

                string[] inputs = { "NR105BE", "BD11AA" };
    
                foreach (string input in inputs)
                {
                    string output = "";
                    if (input.Length == 7)
                    {
                        output = input.Substring(0, 4) + " " + input.Substring(4);
                    }
                    else
                    {
                        output = input.Substring(0, 3) + " " + input.Substring(3);
                    }
                    Console.WriteLine(output);
                }
                Console.ReadLine();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2014-04-17
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多