简体   繁体   中英

C# Convert a string to multidimensional int array

I made a tile level system that uses a multidimensinal array, for example:

new int[,]{
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0,},
            {0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,},
            {0, 0, 0, 0, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0,},
            {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,},

Every specific number represents a block(tile). This is just in code. I want to code a system that can load a level(an multidimensinal int array) That array needs to be converted from a string. How do I do that?

    public static int[,] getLvl(string lvlName = "")
    {
        string readed = "";
        using (StreamReader read = new StreamReader(path))
        {
            readed = read.ReadToEnd();
        }
        return null; //What to put here?!?!?!
    }

EDIT: I do not have yet a format for the file to read. So you can be flexible in that.

I don't think you really need to or should bother trying to serialize it into XML or some other format, since your data storage is so simple.

One easy way is to just store your array in a text file as comma separated values. So one level might have:

0,0,0,1
0,1,1,0
0,1,1,3
3,3,4,1

The String.Split() method is really useful for parsing something simple like this. It allows you to split a string into an array of substrings based on a certain delimiting character.

Step by step:

First you can use var RowArray = MyString.Split('\\n') (the newline character) to split your string into an array of rows. This leaves you with the array:

[0]: "0,0,0,1"
[1]: "0,1,1,0"
[2]: "0,1,1,3"
[3]: "3,3,4,1"

You can sort of see what Split() does here and why that's useful for your case. You can in turn run split each row on ',' leaving with you an array of arrays, which you can very easily convert to exactly the 2D array you're looking for.

The one pitfall here is somewhere, depending on your design needs, one invariant might have to be that in the file all rows will be of the same length. Or if you can't guarantee that, you'll have to write some code so that when turning the below text into an array from an array of rows, you make the width equal to the longest row and fill in blanks with 0s or some other method.

0,0,0,1,6,4
0,1,1,0
0,1,1,3,2,6,3,7,1
3,3,4,1,2,4

The shortest method is using linq, for this format:

 0,0,0,0,0
 1,0,1,0,1
 ....

You can use this sentence:

 int[][] Data =   File.ReadAllLines( path )
                      .Select( s => s.Trim())
                      .Where( s => !string.IsNullOrempty(s))
                      .Select( s => s.Split( ',' )
                                     .Select( token => int.Parse( token ) )
                                     .ToArray( ) )
                      .ToArray( );

 var DataToOneDim = Data.SelectMany( a => a).ToArray();
 var Result = new int[Data[0].Length, Data.Length];
 Buffer.BlockCopy( DataToOneDim, 0, Result, 0, DataToOneDim.Length );

I believe there are a few other posts regarding this, but you can use either XML and parse through each possible dimension or serialize everything at once using the SoapFormatter class. Below is a link to a similar question with some examples:

Convert Multi-Dimensional Array to String and Back

I make it for you fast you can make it better do not Forget the vote :_)

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{

    var array =
        "{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,} , {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,}";

    string input = array;
    string pattern = @"{|}";
    var index = 0;
    var results = new int[100,100];
    foreach (var result in Regex.Split(input, pattern))
    {
        var sp = result.Split(',');
        if (sp.Length <4)
        continue;

        for (int i = 0; i < sp.Count(); i++)
        {
            if (!string.IsNullOrEmpty(sp[i]))
             results[index,i] = Convert.ToInt32(sp[i]);
        }

        index++;
    }
   }
  }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM