输入的每2个字符的C#文本框插入空间

时间:2015-07-12 14:46:49

标签: textbox

有没有办法为文本框中输入的每2个字符插入一个空格?

例如,当用户输入字符串22F188时,我希望它在文本框中显示为22 F1 88

2 个答案:

答案 0 :(得分:0)

[TestMethod]
public void StackOverflowQuestion()
{
    var input = "0123457";
    var temp = Regex.Replace(input, @"(.{2})", "$1 ");
    Assert.AreEqual("01 23 45 7", temp);
}

static string ProcessString(string input)
{
    StringBuilder buffer = new StringBuilder(input.Length*3/2);
    for (int i=0; i<input.Length; i++)
    {
        if ((i>0) & (i%2==0))
            buffer.Append(" ");
        buffer.Append(input[i]);
    }
    return buffer.ToString();
}

Add one space after every two characters and add a character infront of every single character

答案 1 :(得分:0)

您可以使用keyPressed事件。

int i = 0;
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(i < 2){
        i++;
    }
    else{
        i = 0;
        textBox1.Text += ' ';
    }
}