Multidimensional Array from a Txt File

How to create a multidimensional array from a .txt-file?

There's no built in method for it in .NET. What you can do though, is create a multidimensional array from the file lines like so:

private static string[][] ReadAllLines(string filename)
{
string[] allFileLines = File.ReadAllLines(filename);

string[][] arr = new string[allFileLines.Length][];

for (int rowIndex = 0; rowIndex < allFileLines.Length; rowIndex++)
{
// Split by the space character and remove blank entries
arr[rowIndex] = allFileLines[rowIndex].Split(new [] { ' ' },StringSplitOptions.RemoveEmptyEntries);
}

return arr;
}

Read 2d array from txt file in c++

There are a lot of other ways to perform the specific task, but i guess your method is not wrong, and you have just made a simple typing mistake in your second for loop condition. so ill just fix your code for you.
and also you could just input single values at a time as u go.

#include<bits/stdc++.h>
using namespace std;
int main()
{
char arr1[10][10];
cout <<"Reading Start" <<endl;
ifstream rfile("test.txt");
int i,j;
for(i=0;i<6;i++){
for(j=0;j<6;j++){
rfile >> arr1[i][j];
cout << arr1[i][j] << " ";
}
cout << endl;
}

cout <<"\nRead Done" <<endl<<endl;
rfile.close();
}

Output : Sample Image

Multidimensional Array from a txt file

I assume that all of the lines have the same format. We can simply iterate through the lines as below:

string[] lines = File.ReadAllLines(filename);
int len0 = lines.Length;
int len1 = lines[0].Split(':').Length;
string[,] array = new string[len0, len1];
for (int i= 0; i < len0; i++)
{
string line = lines[i];
string[] fields = line.Split(':');
if (fields.Length != len1)
continue; // to prevent error for the lines that do not meet the formatting
for(int j = 0; j < len1; j++)
{
array[i,j] = fields[j];
}
}

read .txt file content into php multi dimensional array

Alives answer gives a result that you probably can work with, but I think associative array is probably the way to go.

I look at each line to see if it has a question number => add new item in array with question number and question text.

If first char is letter and second is a dot, it's an answer => add answer letter as key and text as value.

If it's none of above it's the answer text => add key with ANSWER and value as the correct answer.

I use explode to split the lines. The third argument tells how many parts to split the string in.

With "2" it splits at first space meaning I have the question# as item 1 and question text as item 2 in the array.

https://3v4l.org/ZqppN

// $str = file_get_contents("text.txt");
$str = "1. Abuja, the Federal Capital Territory has -- -- -- -- -- area Council
A. 4
B. 6
C. 7
D. 2
ANSWER: B

2. The Federal Capital Territory is associated with-- -- -- -- -- -- -- vegetation belt
A. Sahel savanna
B. Rainforest
C. Guinea savanna
D. Sudan savanna
ANSWER: C

3. The most significant factor responsible for the ever increasing population of FCT is
A. High birth rate
B. Immigration
C. Death rate
D. CENSUS
ANSWER: B";

$arr = explode("\n", $str);

$res=[];

Foreach($arr as $line){
If($line != ""){
If(is_numeric($line[0])){
Preg_match("/^\d+/", $line, $num);
$res[$num[0]] =["QUESTION" =>explode(" ", $line,2)[1]];
$q = $num[0];
}Else if(ctype_alpha($line[0]) && $line[1] == "."){
$res[$q][$line[0]] = explode(" ", $line, 2)[1];
}Else{
$res[$q]["ANSWER"] = trim(explode(":", $line, 2)[1]);
}
}
}

Var_dump($res);

Read .txt file into a multi dimensional array in php

As far as I understand from your desired output:
Basically inside the loop, instead of setting the output of the line ($data) as a value of the array. I set a sub-array for each row.

$locks = array();
$handle = fopen("lock.txt", "r");
if ($handle) {
$i=0;
while (($line = fgets($handle)) !== false) {
$data = explode("|", $line);
$locks[$i] = array(
1 => $data[0],
2 => $data[1],
3 => $data[2]
);
$i++;
//var_dump($locks);

}
fclose($handle);
} else {
// error opening the file.
}

Which should give the following:

$locks[0][1] = 20
$locks[0][2] = Charlotte Aaaa
$locks[0][3] = XXXX*SALE*O9
$locks[1][1] = 20
$locks[1][2] = Peggy Bbbbb
$locks[1][3] = XXXX*SALE*O8
...
...

How to read text file of data and store it as a multi-dimensional array with Lua

If I understand this correctly, you want to break the lines of text from the file into pieces to create a two-dimensional array.

First, you can loop through lines in a file with a handy method called lines. Assume you have a file object called file. Looping through it line-by-line is as simple as this:

for line in file:lines() do
-- Do something.
end

Using this lines method, I wrote a function called create_array_from_file that I hope has the functionality you described in your question. The function takes a string, filename, as an argument; it uses string.gmatch to break each line into individual elements, splitting lines on commas, which is how you separated elements in your example text file.

-- This pattern means series of 1 or more characters that are not commas.
local MATCH_PATTERN = "[^,]+"

local function create_array_from_file(filename)
local file = assert(io.open(filename, "r"))
local arr = {}
for line in file:lines() do
local row = {}
for match in string.gmatch(line, MATCH_PATTERN) do
table.insert(row, match)
end
table.insert(arr, row)
end
return arr
end

You could change MATCH_PATTERN to whatever you want, based on how your input text files are written; alternatively, could include a second parameter for create_array_from_file to accept a second argument to be used as the pattern provided to string.gmatch.

local function create_array_from_file(filename, pattern)
local file = assert(io.open(filename, "r"))
local arr = {}
for line in file:lines() do
local row = {}
-- Here, `MATCH_PATTERN` is replaced by the function's argument `pattern`.
for match in string.gmatch(line, pattern) do
table.insert(row, match)
end
table.insert(arr, row)
end
return arr
end

This second version offers you more flexibility when splitting the lines of your input files.

Convert the .txt file content into multidimensional array using it's current format

Complex solution with preg_match_all, array_map and array_combine functions:

$data = file_get_contents('array.txt');
$pat = '/intervals \[\d+\]:\s+\Kmin_size = (?P<min_size>\d+(\.\d+)?) \
\s+max_size = (?P<max_size>\d+(\.\d+)?)\s+type = "(?P<type>[^"]*)"/m';

preg_match_all($pat, $data, $m);
$result = array_map(function($a){
return array_combine(['min_size', 'max_size', 'type'], $a);
}, array_map(null, $m['min_size'], $m['max_size'], $m['type']));

print_r($result);

The output:

Array
(
[0] => Array
(
[min_size] => 0
[max_size] => 13.139997023062838
[type] =>
)

[1] => Array
(
[min_size] => 13.139997023062838
[max_size] => 14.763036269953904
[type] => this is a type
)

[2] => Array
(
[min_size] => 14.763036269953904
[max_size] => 17.01
[type] =>
)

[3] => Array
(
[min_size] => 17.01
[max_size] => 18.193
[type] =>
)
)

Explode a .txt file into multidimensional array

Here is the code:

<?php

$data = file_get_contents('File.txt'); // Get the file content
$data = str_replace(array("\n", "\r"), '', $data); // Clear newline characters

$data = explode(':', $data); // Get each record by : at end of line

unset($data[count($data) - 1]); // Clear the last empty element

$final_array = array();
foreach($data AS $row){ // Loop the exploded data
$final_array[] = explode(' = ', $row); // Explode each row by Space=Space to each row of final_array
}

print_r($final_array);

?>


Related Topics



Leave a reply



Submit