如何从字符串中检索每个值并将它们添加到列表中

时间:2017-11-13 21:35:36

标签: c# string int tuples substring

这是我目前在C#中的代码

string myString = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";
var tuple = new List<Tuple<int, int>>();
foreach (var value in myString)
{
    int startPos = myString.IndexOf("value:") + "value:".Length;
    int length = myString.LastIndexOf(", data") - startPos;
    string valuesX = myString.Substring(startPos, length);
    int values = int.Parse(valuesX);
    int startPos2 = myString.IndexOf("data:") + "data:".Length;
    int length2 = myString.LastIndexOf(", end") - startPos2;
    string dataX = myString.Substring(startPos2, length2);
    int data = int.Parse(dataX);
    tuple.Add(Tuple.Create(values, data));
}

我想从字符串中检索值编号和数据编号,并使用整数数据类型

将它们放入列表中

这张照片展示了我想要实现的目标:

picture demonstration

代码根本不起作用,我将不胜感激任何帮助,谢谢

3 个答案:

答案 0 :(得分:2)

第一,你不能像这样循环一个字符串,你需要拆分它。

根据以下假设:

  1. 结构值:#,数据:#,结束永不改变
  2. 值和数据的数字始终为整数
  3. 然后以下内容将起作用。

    string myString             = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";
    List<Tuple<int, int>> tuple = new List<Tuple<int, int>>();
    
    // first split the string on commas so we have a collection to loop through
    string[] splitString = myString.Split(',');
    
    // Assuming the Value:#, Data:#, end structure, we can loop by 3 each time
    for (int i = 0; i < splitString.Length; i = i+3)
    {
        /* Assuming the above structure, we can be sure that
        * i = Value
        * i+1 = Data
        * i+2 = end - which we can ignore
        * all will be integers by assumption so no need to check, just parse
        * Always in string:# pattern so we split on : and take the second item
        */
        int value = Int32.Parse(splitString[i].Split(':')[1]);
        int data  = Int32.Parse(splitString[i + 1].Split(':')[1]);
    
        tuple.Add(Tuple.Create(value, data));
    }
    

答案 1 :(得分:2)

您可以使用正则表达式。以下是我的代码。

string myString = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";

var matches = Regex.Matches(myString, @"value[0-9]*\:([0-9]+) *, * data[0-9]*\:([0-9]+)");
var pairs = new List<(int key, int value)>();
foreach (Match match in matches)
{
    var a = int.Parse(match.Groups[1].ToString());
    var b = int.Parse(match.Groups[2].ToString());
    pairs.Add((a,b));
}

答案 2 :(得分:1)

使用Linq,您可以将字符串处理为子字符串,然后处理List s中的值:

var tuples = myString.Split(new[] { ", end" }, StringSplitOptions.None) ' split into data strings
                     .Select(s => s.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries) ' split into data string pairs
                     .Select(s2 => Int32.Parse(s2.Split(':')[1])).ToList()) ' extract number and make int32 pairs
                     .Where(s => s.Count > 0) ' exclude empty data strings
                     .Select(s => (s[0], s[1])).ToList(); ' create tuples and put in a List