简体   繁体   中英

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

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.

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

Similarly, double parse can be made to be sensitive to different cultures. Some people write a 1,234.5 as 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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