首页 > 解决方案 > padding the middle of a string

问题描述

I have a Textbox field that takes in a string with a character limit of 10. I would like to implement a short hand version because there are a lot of zeros in the string that have to be entered. so an example of the string is T000028999. but id like to key in T28999 and have the zeros padded between the "T" and the "28999" and show up as the T000028999 string in the Textbox field. Is this even possible?

I've tried searching examples on google and have only found ways to pad the beginning and end of the string.

标签: windowsvb.netwinformsvisual-studio-2017

解决方案


您想保留第一个字符,因此您可以使用它oldString.Chars(0)来获取它。

您想要字符串的其余部分: oldString.Substring(1),并且可以使用您选择的字符将其填充到您需要的宽度PadLeft,如下所示:

Dim newString = oldString.Chars(0) & oldString.Substring(1).PadLeft(9, "0"c)

最好oldString在执行此操作之前检查至少 1 个字符,否则.Chars(0)会出错。

或者,您可以插入所需数量的“0”的新字符串:

Dim newString = oldString.Insert(1, New String("0"c, 10 - oldString.Length))

执行格式化的一个好地方是控件的Validating事件处理程序。(TextChanged 事件处理程序不是一个好地方,因为它会干扰用户的输入。)


参考:


推荐阅读