【发布时间】:2020-04-14 20:11:58
【问题描述】:
我有以下问题。 我有这些字符串,它们之间有空格。
"+name:string" "+age:int"
我用这段代码分割它们:
List<string> stringValueList = new List<string>();
stringValueList = System.Text.RegularExpressions.Regex.Split(stringValue, @"\s{2,}").ToList<string>();
现在 List 的元素是这样的
"+name:string"
"+age:int"
现在我想拆分这些字符串并创建对象。 这看起来像这样:
// Storing the created objects in a List of objects
List<myObject> objectList = new List<myObject>();
for(i = 1; i < stringValueList.Count ; i+=2)
{
myObject object = new myObject();
object.modifier = '+';
object.name = stringValueList[i-1].Trim('+'); // out of the example the object.name should be "name"
object.type = stringValueList[i]; // out of the example the object.type value should "string"
objectList.Add(object);
}
最后我应该得到两个具有这些值的对象:
List<myObject> objectList{ myObject object1{modifier = '+' , name ="name" , type="string"}, myObject object2{modifier='+', name="age" type="int"}}
但我的结果是这样的:
List<myObject> objectList {myObject object1 {modifier='+', name="name:string" type="+age:int"}}
所以我得到 1 个对象,而不是 2 个对象。它将两个字符串都放入第一个对象的元素中。
谁能帮帮我?我想我的问题出在 for 循环中,因为 i-1 值是列表中的第一个字符串,而 i 是第二个字符串,但我无法更改。
【问题讨论】:
标签: c# string list for-loop split