如何从包含文本字符串的列表中提取整数值?

时间:2017-08-29 03:08:22

标签: c#

我有以下列表:

    List<string> scores = new List<string>
    {
        "1 point",
        "2 points",
        "5 points",
        "10 points",
        "15 points",
        "20 points",
        "25 points",
        "30 points",
        "40 points",
        "50 points"
    };

我的代码GUI选择其中一个并返回0到9之间的值。

如果给出0-9号码,如何将数字从1转换为50?

2 个答案:

答案 0 :(得分:3)

正如this link所示,正则表达式可以在这里提供帮助:

给定一个整数(介于0到9之间,事先进行检查以确保它在该范围内):

resultString = Regex.Match(scores[x], @"\d+").Value;
var points = Int32.Parse(resultString);

P.S。您需要using System.Text.RegularExpressions;

答案 1 :(得分:2)

如果通过我的代码GUI选择其中一个,则表示从此列表中进行选择,您想知道它可以尝试index

var testInput = "10 points";
var scores = new List<string>
{
    "1 point",
    "2 points",
    "5 points",
    "10 points",
    "15 points",
    "20 points",
    "25 points",
    "30 points",
    "40 points",
    "50 points"
}; 
var index = scores.IndexOf(testInput); //<- Returns 3

如果您的意思是3,并且想要将其转换为10 points,则可以执行以下操作。

var index = 3;
var scores = new List<string>
{
    "1 point",
    "2 points",
    "5 points",
    "10 points",
    "15 points",
    "20 points",
    "25 points",
    "30 points",
    "40 points",
    "50 points"
}; 
var score = scores[index]; //<- Returns 10 points