将这样的字符串传递给后面的代码:
0,-1 | 1,-1 | 2,-1 | 3,-1 | 4,-1 | 5,-1 | 6,-1 | 7,-1 | 8,-1
我需要能够为每个“ |”分配“,”符号前后的值在字符串中退出的符号,分隔成多个变量,第一个值“ line”(在“,”之前),下一个值“ group”(在“,”之后)。
现在我正在尝试此操作,但是在从string []转换为string时遇到一些问题。
public static string GuardarGrupos(string parametro){
var data = parametro.Split(Convert.ToChar("|"));
var datos = "";
string[] linea;
var grupo = "";
//Iterate through each of the letters
foreach (var check in data)
{
datos = data[0];
linea = data[0].Split(Convert.ToChar(","));
}
return linea;
}
任何想法我该如何实现?
答案 0 :(得分:1)
设置class
或struct
来保存您的值:
public class DataObject
{
public string X {get; set;}
public string Y {get; set;}
}
返回类型为List<T>
的{{1}}
DataObject
有了public static List<DataObject> GuardarGrupos(string parametro){
//List to return
List<DataObject> returnList = new List<DataObject>();
//Split the string on pipe to get each set of values
var data = parametro.Split('|'); //No need to do a convert.char(),
//String.Split has an overload that takes a character, use single quotes for character
//Iterate through each of the letters
foreach (var check in data)
{
//Split on comma to get the individual values
string[] values = check.Split(',');
DataObject do = new DataObject()
{
X = values[0];
Y = values[1];
};
returnList.Add(do);
}
return returnList;
}
后,就可以使用List<DataObject>
和linq
来形成行和组:
string.Join
答案 1 :(得分:1)
创建一个存储您检索到的值的类,而不是使用局部变量。然后您可以根据需要处理/操纵这些值。
public class MyData
{
public string Datos { get; set; }
public string Linea { get; set; }
public string Grupo { get; set; }
}
public static List<MyData> myFunction(string parametro)
{
List<MyData> result = new List<MyData>();
var data = parametro.Split(Convert.ToChar("|"));
foreach (var check in data)
{
MyData temp = new MyData();
var line = check.Split(',');
temp.Datos = line[0];
temp.Linea = line[1];
temp.Grupo = check;
result.Add(temp);
}
return result;
}
static void Main(string[] args)
{
var t = myFunction("0,-1|1,-1|2,-1|3,-1|4,-1|5,-1|6,-1|7,-1|8,-1");
}
答案 2 :(得分:0)
这是一个可靠的解决方案,它只是对字符串的简单迭代。
void Main()
{
var xs = "0,-1|1,-1|2,-1|3,-1|4,-1|5,-1|6,-1|7,-1|8,-1";
var stack = new Stack<Pair>();
stack.Push(new Pair());
foreach(var x in xs)
if(x == '|')
stack.Push(new UserQuery.Pair());
else
stack.Peek().Accept(x);
foreach (var x in stack.Reverse())
Console.WriteLine(x);
}
sealed class Pair
{
Action<char> _Accept;
readonly List<char> Line = new List<char>();
readonly List<char> Group = new List<char>();
public Pair()
{
_Accept = x => Line.Add(x);
}
public void Accept(char c)
{
if(c == ',')
_Accept = x => Group.Add(x);
else
_Accept(c);
}
public override string ToString()
{
return "Line:" + new string(Line.ToArray()) + " Group:" + new string(Group.ToArray());
}
}