c# - 如果长度为 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 += " ";
}
}
任何帮助,将不胜感激。谢谢。
解决方案
您可以使用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, " ");
}
推荐阅读
- elasticsearch - 日期映射在 Kibana 和 ES 中不起作用
- r - dplyr 按字符串匹配分组
- php - Wordpress 自定义图像裁剪器小部件
- mysql - Mysql 中的 substring_index 分隔符
- openshift - 如何在 openSHIFT ORIGIN 中公开容器化的 asp.net 核心 web api 应用程序
- openssl - 从 PEM 格式证书和 PEM 格式公钥生成 DER 格式公钥
- c# - 如何使用 C# 在 IIS 中启用 HTTPS?
- python - 我怎样才能不丢失我在 Anaconda 3 python 3.6.3 上安装的所有软件包
- reactjs - 在 Typescript React 中声明可选的事件回调
- angular - 获取 Ionic 2 中的 dimensions.contentTop 属性值