从字符串输入中提取值

时间:2019-11-16 11:38:12

标签: c# string

我正在尝试一种有效的方法来拆分字符串。我有一个以下格式的字符串,代表一个值。

string input = "1A2B3C4D5DC";

我必须获取每个字符旁边的数字值,以便我可以计算最终值。 目前,我正在这样做,这很好,您能建议我一种更好的方法吗?

    public double GetValue(string input)
    {
        string value;
        int beginIndex = 0, endIndex = 0, unit1 = 0, unit2 = 0, unit3 = 0, unit4 = 0, unit5 = 0;
        input = input.Replace("cd", "zz");
        if (input.ToLower().Contains("a"))
        {
            endIndex = input.ToLower().IndexOf('a');
            value = input.Substring(beginIndex, endIndex - beginIndex);
            int.TryParse(value, out unit1);
            beginIndex = endIndex + 1;
        }

        if (input.ToLower().Contains("b"))
        {
            endIndex = input.ToLower().IndexOf('b');
            value = input.Substring(beginIndex, endIndex - beginIndex);
            int.TryParse(value, out unit2);
            beginIndex = endIndex + 1;
        }

        if (input.ToLower().Contains("c") )
        {
            endIndex = input.ToLower().IndexOf('b');
            value = input.Substring(beginIndex, endIndex - beginIndex);
            int.TryParse(value, out unit3);
            beginIndex = endIndex + 1;
        }

        if (input.ToLower().Contains("d"))
        {
            endIndex = input.ToLower().IndexOf('d');
            value = input.Substring(beginIndex, endIndex - beginIndex);
            int.TryParse(value, out unit4);
            beginIndex = endIndex + 1;
        }

        if (input.Length > beginIndex + 2)
        {
            value = input.Substring(beginIndex, input.Length - beginIndex - 2);
            int.TryParse(value, out unit5);
        }

        return (unit1 * 10 + unit2 * 20 + unit3 * 30 + unit4 * 40 + unit5 * 50); //some calculation
    }

可能的输入可以是:21A34DC,4C,2BDC,2B。基本上它们都是可选的,但如果存在,则必须按相同的顺序

5 个答案:

答案 0 :(得分:1)

如果您只想从字符串中提取数字,请使用正则表达式:

string input = "1A2B3C4D5DC";           
var resultString = Regex.Replace(input, @"[^0-9]+", "");

或linq方式:

string input = "1A2B3C4D5DC";            
var  resultString = new String(input.Where(Char.IsDigit).ToArray());

答案 1 :(得分:1)

您可以使用正则表达式查找字符串中的所有数字:

string input = "1A2B3C4D5DC";
Regex rx = new Regex(@"\d+");
// Regex rx = new Regex(@"-?\d+"); // this one includes negative integers
var matches = rx.Matches(input);

int[] numbers = matches.OfType<Match>()
                       .Select(m => Convert.ToInt32(m.Value))
                       .ToArray();

对结果数组进行必要的计算。

答案 2 :(得分:0)

仅查看您的代码,就有很多重复的代码,因此按原样重构它并使用映射字典可能是很好的解决方法

类似这样的东西

   public static  double GetValue(string input)
    {
        var map = new Dictionary<string, int>()
        {
             {"a", 10 }, {"b", 20}, {"c", 30}, {"d", 40}
        };
        int result = 0;
        foreach(var i in map)
        {
            int endIndex, outValue;
            string value;
            endIndex = input.ToLower().IndexOf(i.Key);
            value = input.Substring(endIndex -1,  1);
            int.TryParse(value, out outValue);

            result += (i.Value * outValue);
        }

        return result;
    }

答案 3 :(得分:0)

以下是我的代码

public double GetValue(string input)
{
    input)= input)();
    string value;
    int aValue = 0, bValue = 0, cValue = 0, dvalue = 0, cdValue = 0;

    if (match.Groups[5].Success && !string.IsNullOrEmpty(match.Groups[5].Value))
        {
            string val = match.Groups[5].Value;
            if (!int.TryParse(val.Substring(0, val.Length - 2), out cdValue))
            {
                return -1;
            }
        }
        if (match.Groups[4].Success && !string.IsNullOrEmpty(match.Groups[4].Value))
        {
            string val = match.Groups[4].Value;
            if (!int.TryParse(val.Substring(0, val.Length - 1), out dvalue))
            {
                return -1;
            }
        }
        if (match.Groups[3].Success && !string.IsNullOrEmpty(match.Groups[3].Value))
        {
            string val = match.Groups[3].Value;
            if (!int.TryParse(val.Substring(0, val.Length - 1), out cValue))
            {
                return -1;
            }
        }
        if (match.Groups[2].Success && !string.IsNullOrEmpty(match.Groups[2].Value))
        {
            string val = match.Groups[2].Value;
            if (!int.TryParse(val.Substring(0, val.Length - 1), out bValue))
            {
                return -1;
            }
        }
        if (match.Groups[1].Success && !string.IsNullOrEmpty(match.Groups[1].Value))
        {
            string val = match.Groups[1].Value;
            if (!int.TryParse(val.Substring(0, val.Length - 1), out aValue))
            {
                return -1;
            }
        }
        return (aValue  * 10 + bValue * 20 + cValue * 30 + dvalue * 40 + cdValue * 50); //some calculation
}

答案 4 :(得分:0)

告诉我这是否产生预期的输出:

    static void Main(string[] args)
    {
        int sum = GetValue("1A2B3C4D5DC");
        // {1,2,3,4,5} = 10*(1+2*2+3*3+4*4+5*5) = 550
    }

    public static int GetValue(string input)
    {
        // make input all lowercase
        input = input.ToLower();
        // replace terminator dc with next letter to
        // avoid failing the search;
        input = input.Replace("dc", "e");

        // initialize all unit values to zero
        const string tokens = "abcde";
        int[] units = new int[tokens.Length];

        // keep track of position of last parsed number
        int start = 0;
        for (int index = 0; index < tokens.Length; index++)
        {
            // fetch next letter
            char token = tokens[index];
            // find letter in input
            int position = input.IndexOf(token, start);
            // if found
            if (position>start)
            {
                // extract string before letter
                string temp = input.Substring(start, position-start);
                // and convert to integer
                int.TryParse(temp, out units[index]);
            }
            // update last parsed number
            start = position+1;
        }
        // add unit values, each one worth +10 more than the
        // previous one. 
        //
        // {x,y,z} = 10*x + 20*y + 30*z
        int sum = 0;
        for (int i = 0; i < units.Length; i++)
        {
            sum += 10*(i+1)*units[i];
        }
        return sum;
    }

}
  

请在问题中添加一些带有预期结果的测试用例,以确保我们的答案正确。

"1A2B3C4D5DC" => 550
???