Вопрос

I have a text file that consist of

name,definition;
name1,definition;
name2, definition;

i know how to split the the string that is being taken into the script from the text file but i dont know how to get it all into a 2darray or jagged array.

it should look like this after words

array[0][0] = name;
array[0][1] = definition;

SORRY, i forgot to say what language, its in C#

Это было полезно?

Решение

Here's your solution in JavaScript. note If your row values can contain quotes, new lines, or escaped delimiters more parsing is necessary.

http://jsfiddle.net/N4YYA/

var result = [];
var txt = document.getElementById("test").value;
// get lines
var lines = txt.split(";");
for(var i=0; i<lines.length; i++) {
    // get and trim whitespace off the line
    var line = lines[i].replace(/(^[\s\r\n]*|[\s\r\n]*$)/g, "");
    var values = line.split(",");
    var row = [];
    for(var j=0; j<values.length; j++) {
        // get and trim whitespace off each value
        var value = values[j].replace(/(^[\s\r\n]*|[\s\r\n]*$)/g, "");
        // add it to your row array
        row.push(value);
    }
    // add row to results
    result.push(row);
}

// debug show result
var o = document.getElementById("outp");
for(var x=0; x<result.length; x++)
    o.innerHTML += result[x].toString() + "<br/>";

Другие советы

In C#:

string[][] array = inputString.Split(';').Select(x => x.Split(',')).ToArray();

and if you want to include the trim for some reason:

string[][] array = inputString.Split(';').Select(x => x.Split(',').Select(y=>y.Trim()).ToArray()).ToArray();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top