如何检查字符串是否遵循美国货币的格式?

EntomberExarch

我正在解决一个问题,希望我从用户那里获得字符串输入,并通过一种方法检查它是否通过美国货币模式运行,该方法将检查每个字符。它必须是方法中使用的字符串。金额可以是从1美元到一千美元之间的任何值,但必须输入$ x.xx,$ xx.xx,$ xxx.xx格式,只要用户输入的金额与上述格式一致即可,我的程序应该输出其“有效”的任何内容都是“无效格式”的输出。第一个字符必须为“ $”,并且我不能使用正则表达式。

我得到用户输入,然后使用.NullOrWhiteSpace对其进行验证。然后将保存用户输入的字符串值发送到我创建的方法中。从这一点上我不知道如何继续。我尝试过.ToCharArray,我也尝试过编写冗长而复杂的if语句,并且我已经研究了几个小时,但找不到可靠的方法来写出来。

 class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("enter amount between $1.00 and $1000.00");
        string valueUS = Console.ReadLine();
        while (string.IsNullOrWhiteSpace(valueUS))
        {
            Console.WriteLine("Please enter in an amount");
            valueUS = Console.ReadLine();
        }

        currencyChecker(valueUS);

    }

    public static string currencyChecker(string currencyString)
    {

        char[] currencyArray;
        currencyArray = currencyString.ToCharArray();
        for (int i = 0; i < currencyArray.Length; i++)
        {

            if (currencyArray[0] == '$')
            {

            }

        }
        return currencyString;

下面的方法应检查用户输入的每个字符,并验证其是否与上述美国货币模式相匹配,并输出其“有效”的任何其他内容都应报告为“无效”

Zohar Peled

通常,您将对此类内容使用正则表达式。一个简单的正则表达式是^\$\d+.\d\d$基本上,这意味着字符串应以$符号开头,最后应有一个数字,一个点和另外两个数字。

但是,这可以不使用正则表达式而完成,并且由于它看起来像是一项家庭作业,因此我将向您介绍正确的方向。

因此,您需要测试以开头的字符串$,右侧第3个字符为.,其他所有字符均为数字。

您的方法应返回表示有效/无效结果的布尔值-因此您应执行以下操作:

 static bool IsCurrency(string currency)
 {

     // Check if the string is not null or empty - if not, return false

     // check if the string is at least 5 chars long, since you need  at least $x.xx - if not, return false

     // Check if the first char is $ - if not, return false

     // Check if the 3rd char from the end is . - if not, return false

     // check if all the other chars are digits - if not, return false


     // If all checks are valid -
     return true;
 }

请注意,测试的顺序很关键,例如,如果您检查右边的第3位数字是否为a,.然后再检查至少5位数字,则可能会尝试检查仅2位数字长的字符串并得到异常。

由于这(可能)是家庭作业,因此我将把代码编写部分留给您,因此您实际上会从中学到一些东西。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章