如何从C#中的字符串输入中删除非数字字符?

问题描述 投票:0回答:1

我正在制作一个计算器作为 Windows 窗体应用程序。为了避免 FormatException,我需要从 TextBox 中删除空格、特殊符号或字母等符号。

if (textBox1.Text[textBox1.Text.Length - 1] == '.')
    textBox1.Text += '0';
for (int i = 0; i < textBox1.Text.Length; i++)
    if (!((textBox1.Text[i] == 0) || (textBox1.Text[i] == 1) ||
        (textBox1.Text[i] == 2) || (textBox1.Text[i] == 3) ||
        (textBox1.Text[i] == 4) || (textBox1.Text[i] == 5) ||
        (textBox1.Text[i] == 6) || (textBox1.Text[i] == 7) ||
        (textBox1.Text[i] == 8) || (textBox1.Text[i] == 9) ||
        (textBox1.Text[i] == '.')))
            textBox1.Text[i] = '';
    
number = Convert.ToInt32(textBox1.Text);
calculatorBLL.OperatorClicked(Operator, number);

我的第一个想法是使用

Remove(i)
函数,但它会删除从无效字符开始的所有字符,所以我决定使用
textBox1.Text[i] = ''
代替。但是,不允许分配空字符文字。 此外,这两种方法似乎都不起作用:
'string.this[int]' cannot be assigned to -- it is read only

c# string textbox
1个回答
0
投票

我认为,根据数字字符创建一个新字符串更简单,而不是从 TextBox 值中删除非数字字符。另外,最好使用 Char.IsDigit Method 方法,而不是检查每个基数 10 数字。然后你的代码就变成了

if (textBox1.Text[textBox1.Text.Length - 1] == '.')
    textBox1.Text += '0';
string numstr = "";
for (int i = 0; i < textBox1.Text.Length; i++)
    if (textBox1.Text[i].IsChar() || textBox1.Text[i] == '.')
        numstr += textBox1.Text[i];
    
number = Convert.ToInt32(numstr);
calculatorBLL.OperatorClicked(Operator, number);
© www.soinside.com 2019 - 2024. All rights reserved.