将字符串中的所有数字提取到数组中

时间:2015-05-08 05:52:21

标签: c# arrays string

我有一个像这样的字符串

+3.15% price per day(+63.00% price at day 20)

我希望能够将它导出到一个数组中,所以它变成了这样的

{3.15 , 63.00, 20}

有人可以帮我吗?我现在真的陷入困境,因为我不是百分之百确定如何处理它:\我之所以这样做是因为我想要将该字符串中的数字乘以4之类的数字,所以结果将成为

+12.60% price per day(+252.00% price at day 20)

以下是所有可能的案例

-3.15% price per day(-63.00% price at day 20)

=>  -12.60% price per day(-252.00% price at day 20)

+0.76 price per day(+15.20 price at day 20)

=>  +3.04 price per day(+60.80 price at day 20)

2 个答案:

答案 0 :(得分:2)

// export numbers
string input = "+3% price per day(+60% price at day 20)";
int[] array = Regex.Matches(input, @"\d+").OfType<Match>().Select(e => int.Parse(e.Value)).ToArray();

// replace numbers
double k = 3;
string replaced = Regex.Replace(input, @"\d+", e => (int.Parse(e.Value) * k).ToString());

// replace only percents
k = 4;
string replacedPercents = Regex.Replace(input, @"(\d+)%", e => (int.Parse(e.Groups[1].Value) * k).ToString() + "%");

// floating conversion
input = "+0.87 price per day(+63.00 price at day 20)";
string replacedFloating = Regex.Replace(input, @"\+(\d+\.(\d+)|\d+)", e => "+" + (double.Parse(e.Groups[1].Value, CultureInfo.InvariantCulture) * k).ToString(e.Groups[2].Length == 0 ? "0" : "0." + new string('0', e.Groups[2].Length), CultureInfo.InvariantCulture));

// floating conversion with negatives
input = "-0.87 price per day(+63.00 price at day 20)";
string replacedFloatingNegative = Regex.Replace(input, @"([+-])(\d+\.(\d+)|\d+)", e => e.Groups[1].Value + (double.Parse(e.Groups[2].Value, CultureInfo.InvariantCulture) * k).ToString(e.Groups[3].Length == 0 ? "0" : "0." + new string('0', e.Groups[3].Length), CultureInfo.InvariantCulture));

已取代

+9% price per day(+180% price at day 60)

replacementPercents

+12% price per day(+240% price at day 20)

replacementFloating

+12.60 price per day(+252.00 price at day 20)

replacementFloatingNegative

-3.48 price per day(+252.00 price at day 20)

答案 1 :(得分:-1)

char[] test = new Char[10];
        string val = "+3% price per day(+60% price at day 20)";
        try
        {
            for (int i = 0, j = 0; val[i] != null ; i++)
            {
                if (Char.IsDigit(val[i]))
                {
                    test[j++] = val[i];
                    Console.WriteLine(val[i]);
                }

            }
        }
        catch (Exception){ }

根据需要使用测试阵列