首页 > 解决方案 > 如果长度为 6 个字符,如何在文本框中的第 3 个字符后添加空格,如果长度为 7 个字符,如何在第 4 个字符后添加空格

问题描述

我试图根据总字符数在文本框中的第 3 个或第 4 个字符之后添加一个空格。

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

文本框中 7 个字符的示例

在失去焦点之前

失去焦点

文本框中 6 个字符的示例

在失去焦点之前

失去焦点

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

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

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

标签: c#wpfwindows

解决方案


您可以使用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, " ");
}

推荐阅读