简体   繁体   English

C#检查字符串是否包含字符但允许与其他特定字符一起使用

[英]C# check if the string contains a character but allowed with other specific character

I have a problem with my unit converter app. 我的单位转换器应用程序有问题。 I`m trying to prevent users from using any other characters than numbers but I need to allowed them to use "." 我试图阻止用户使用数字以外的任何其他字符,但我需要允许他们使用“。” How can I do this? 我怎样才能做到这一点?

I spend like 2 days on that with no luck. 我花了大约两天的时间,没有运气。 Please help. 请帮忙。 Here is my code. 这是我的代码。

 public string[] YardsToMeters(string yards)
        {
            if(yards == null || yards.Contains(" "))
            {
                string[] str = new string[1];
                str[0] = "Please enter some values";

                return str;

            }

Here I`m checking for allowed characters: 在这里,我正在检查允许的字符:

            else if((Regex.IsMatch(yards, @"^\d+$") == true) || (yards.Contains(".") && yards[0] != '.'
                 || (yards.Contains('\n')) && (Regex.IsMatch(yards, @"^\d+$") == true) && !yards.Contains(".")))
            {

                if (!yards.Contains('\n') && Regex.IsMatch(yards, @"^\d+$") == true)
                {
                    double d = double.Parse(yards, CultureInfo.InvariantCulture) * 0.9144f;

                    string[] array = new string[1];
                    array[0] = d.ToString();

                    return array;

                }

                else if(Regex.IsMatch(yards, @"^\d+$") == true || yards.Contains(".") && yards[0] != '.')
                {
                    double[] doubles = new double[yards.Split("\r\n").Count()];

                    for (int i = 0; i < yards.Split("\r\n").Count(); i++)
                    {
                        if (yards.Contains("."))
                        {
                            double value = Convert.ToDouble(yards.Split("\r\n")[i].Replace('.',','));
                            doubles[i] += value;

                            string.Format("{0}", value * 0.9144f);
                        }

                        else
                        {
                            double value = Convert.ToDouble(yards.Split("\r\n")[i]);
                            doubles[i] += value;

                            string.Format("{0}", value * 0.9144f);
                        }


                    }

                    string[] strings = new string[doubles.Length];

                    for (int i = 0; i < yards.Split('\n').Length; i++)
                    {
                        strings[i] = string.Format("{0}", doubles[i] * 0.9144f);
                    }

                    return strings;
                }
                else
                {
                    string[] str = new string[1];
                    str[0] = "Please use numbers only!";

                    return str;
                }

            }
            else
            {

                string[] str = new string[1];
                str[0] = "Please use numbers only! Enter is also not allowed";

                return str;

            }
        }

Please help me with that. 请帮我。

I think you've reached a point where you've lost sight of the goal and you've just been endlessly modifying and tweaking a bad solution to try and cover all the cases where it falls down 我认为您已经达到了无法实现目标的地步,并且不断地修改和调整一个错误的解决方案,以尝试解决所有失败的情况

Yards to Metres -> Multiply yards by 0.9144f 码到米->码数乘以0.9144f

public double YardsToMetres(double yards){ //not sure why you're using string everywhere
    return yards * 0.9144f;
}


public void YardsTextbox_TextChanged(object sender, EventArgs e){
    try{
        double y = double.Parse(_yardsTextbox.Text);
        MessageBox.Show("In metres:" + YardsToMetres(y));
    } catch(FormatException ex){
        MessageBox.Show("The value you entered (" + _yardsTextbox.Text + ") cannot be converted to a number. Enter a number");
    }
}

This is an example, knowing nothing about your UI.. It's a recommendation that you split off the conversion code from the rest of the code. 这是一个示例,对您的用户界面一无所知。建议您将转换代码与其余代码分开。 It should take a number and return a number (don't make everything string just because the input/output supply/require it). 它应该带一个数字并返回一个数字(不要仅仅因为输入/输出提供/要求而将所有字符串都设为字符串)。

Your input routine that collects data from the user should parse their input into a number ready for the converter. 您从用户收集数据的输入例程应将其输入解析为准备好转换器的数字。 If it fails to parse, ask them to correct it. 如果解析失败,请他们更正。 Don't get too deep and meaningful/complex over this - just try to parse it, and if it fails, tell the user it failed - they'll work out what they did wrong. 对此不要过于深入和有意义/复杂-尝试解析它,如果失败,则告诉用户失败-他们将找出他们做错了什么。 You can do SOME limited amount of help, like trimming whitespace off the start if you want (actually double.parse ignores whitespace so it's unnecessary) but i'd perhaps stop short of stripping out all non numbers etc, because youre then doing large amount of manipulation of th data the user entered, doing calcs on it and the user has no idea (unless you tell them) what data you ended up doing your calcs on. 您可以提供一些有限的帮助,例如,如果需要的话,一开始就修剪空白(实际上double.parse会忽略空白,因此这是不必要的),但我可能会停止删除所有非数字等,因为您这样做了用户输入的数据的操作,进行计算的结果,并且用户不知道(除非您告诉他们)最终要进行计算的数据是什么。

If they write 0xFF80, and expect their hex number (equivalent of 65,408) to be converted to mtres, they might be surprised if you've stripped out the xFF, and then done the calc on 80 如果他们写0xFF80,并期望将其十六进制数(相当于65,408)转换为mtres,则如果您剥离了xFF,然后对80进行计算,他们可能会感到惊讶

Similarly, double parse can be made to be sensitive to different cultures. 同样,可以使双重解析对不同的文化敏感。 Some people write a 1,234.5 as 1.234,5. 有人将1,234.5写为1.234,5。 If you decide to strip out commas because theyre thousand separators, you end up ruining someone's decimal number if they use comma as the decimal separator. 如果您决定删除逗号(因为它们是千位分隔符),那么如果某人使用逗号作为十进制分隔符,那么最终将破坏某人的十进制数字。 Consider carefully how deep you want to get into checking and helping the user form a number correctly; 仔细考虑您想深入检查并帮助用户正确形成数字的深度; you're better to just try and work with what they gave you and if it failed, tell them 您最好尝试使用他们给您的东西,如果失败了,告诉他们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM