将字符串赋值到多维数组中
本文关键字:数组 字符串 赋值 | 更新日期: 2023-09-27 18:08:40
假设下面有字符串
[["Fri, 28 Mar 2014 01:00:00 +0000",0.402053266764,"1 sold"],["Thu, 03 Apr 2014 01:00:00 +0000",6.5,"1 sold"]];
如何将这组字符串赋值到数组中?
预期结果:
string[,] items = {
{ "Fri, 28 Mar 2014 01:00:00 +0000", "0.402053266764", "1 sold"},
{ "Thu, 03 Apr 2014 01:00:00 +0000", "6.5", "1 sold"}
}
暴力攻击,可能有更好的解决方案
string input ="[['"Fri, 28 Mar 2014 01:00:00 +0000'",0.402053266764,'"1 sold'"],['"Thu, 03 Apr 2014 01:00:00 +0000'",6.5,'"1 sold'"]]";
string temp = input.Replace("[", "");
string[] records = temp.Split(new char[] {']'}, StringSplitOptions.RemoveEmptyEntries);
string[,] output = new string[records.Length, 3];
int recno = 0;
foreach(string record in records)
{
Console.WriteLine(record);
string[] fields = record.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
output[recno,0] = string.Join(",", fields[0], fields[1]);
output[recno,1] = fields[2];
output[recno,2] = fields[3];
recno++;
}
for(int x = 0; x <= output.GetUpperBound(0); x++)
{
for(int y = 0; y <= output.GetUpperBound(1); y++)
Console.Write("INDEX[" +x + "," + y +"]=" + output[x, y] + ";");
Console.WriteLine();
}
string inputString; //Your original string
inputString=inputString.Replace('[',' '); //Removes left bracket
inputString=inputString.Substring(0,inputString.Count()-2); //Removes last two right brakets
var arrayOfStrings=inputString.Split(']'); //Split on right bracket
for(int i=1; i < arrayOfStrings.Count() -1; i++){
arrayOfStrings[i]=arrayOfStrings[i].Substring(1); //Removes the "," at the start of the 2nd to the n-1th elements
}