Convert a string to multidimensional array - c#

I have a matrix, which is read from the console. The elements are separated by spaces and new lines. How can I convert it into a multidimensional int array in c#? I have tried:
String[][] matrix = (Console.ReadLine()).Split( '\n' ).Select( t => t.Split( ' ' ) ).ToArray();
but when I click enter, the program ends and it doesn't allow me to enter more lines.
The example is:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9

int[,] Matrix = new int[n_rows,n_columns];
for(int i=0;i<n_rows;i++){
String input=Console.ReadLine();
String[] inputs=input.Split(' ');
for(int j=0;j<n_columns;j++){
Matrix[i,j]=Convert.ToInt32(inputs[j]);
}
}
you can try this to load the matrix

First things first, Console.ReadLine() reads a single line from the input. So in order to accept multiple lines you need to do 2 things:
Have a loop which allows the user to continue entering lines of data. You could let them go until they leave a line blank, or you could fix it to 5 lines of input
Store these "lines" of data for future processing.
Assuming the user can enter any number of lines, and a blank line (just hitting enter) indicates the end of data entry something like this will suffice
List<string> inputs = new List<string>();
var endInput = false;
while(!endInput)
{
var currentInput = Console.ReadLine();
if(String.IsNullOrWhitespace(currentInput))
{
endInput = true;
}
else
{
inputs.Add(currentInput);
}
}
// when code continues here you have all the user's input in separate entries in "inputs"
Now for turning that into an array of arrays:
var result = inputs.Select(i => i.Split(' ').ToArray()).ToArray();
That will give you an array of arrays of strings (which is what your example had). If you wanted these to be integers you could parse them as you go:
var result = inputs.Select(i => i.Split(' ').Select(v => int.Parse(v)).ToArray()).ToArray();

// incoming single-string matrix:
String input = #"1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9";
// processing:
String[][] result = input
// Divide in to rows by \n or \r (but remove empty entries)
.Split(new[]{ '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
// no divide each row into columns based on spaces
.Select(x => x.Split(new[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries))
// case from IEnumerable<String[]> to String[][]
.ToArray();
result:
String[][] result = new string[]{
new string[]{ "1","2","3","4","5" },
new string[]{ "2","3","4","5","6" },
new string[]{ "3","4","5","6","7" },
new string[]{ "4","5","6","7","8" },
new string[]{ "5","6","7","8","9" }
};

It can be done in multiple ways
You can read a single line containing multiple numbers separated by a char, split by that char obtaining an array of ints and then you should fetch a matrix.
With out-of-the-box linq there is no trivial way for the fetching step and i think it is not really the case to use third-party libraries from codeplex like LinqLib or something.

Related

Replacing value before space?

I want to replace only the value before space
for example:
1. 1 3
2. 23 5
3. 650 300
4. 1350 19
would be:
1. 2 3
2. 55 5
3. 950 300
4. 5602 19
I only need to change the value before space... after space should remain same. Every value is in a separate row. Before space value can be 1 to 4 digits and after space value can be 1 to 3 digits.
string num = "650 3";
string afterspace = num.Substring(0, 4);
Console.WriteLine(afterspace);
string beforespace = num.Substring(4);
Console.WriteLine(beforespace);
If this is a space separated string, you can try the bewlo approach..
var arr = str.Split(' ');
arr[0] = newValue;//here you can use the index and new value to assign the new value.
str = string.Join(" ",arr);

Comparing 2 strings c#

So I have a string which I split in half. Now I need to compare both parts of the string and output has to be all the elements that are the same in both of them.
I noticed some people using Intersect, but I don't know why it doesn't work for me, I get really weird output if I use it.
So here is my code:
string first= "1 3 6 8 4 11 34 23 3 1 7 22 24 8"
int firstLength = first.Length;
int half = firstLength / 2;
string S1 = first.Substring(0, half);
string S2= first.Substring(half, half);
var areInCommon = S1.Intersect(S2);
Console.WriteLine("Numbers that these 2 strings have in common are: ");
foreach (int i in areInCommon)
Console.WriteLine(i);
So in this case output would be: 1, 3 and 8.
Any help would be appreciated.
You were close what you really want is arrays of the numbers not arrays of chars... you can get that with the split function.
string first= "1 3 6 8 4 11 34 23 3 1 7 22 24 8"
int firstLength = first.Length;
int half = firstLength / 2;
string S1 = first.Substring(0, half);
string S2= first.Substring(half, half);
var areInCommon = S1.Split(" ".ToArray()).Intersect(S2.Split(" ".ToArray());
Console.WriteLine("Numbers that these 2 strings have in common are: ");
foreach (var i in areInCommon)
Console.WriteLine(i);
A note about using ToArray():
I use ToArray() out of habit and the reason is that if you want to pass in parameters you can't do it without this construct. For example if the data looked like this:
string first= "1, 3, 6, 8, 4, 11, 34, 23, 3, 1, 7, 22, 24, 8"
then we would need to use
.Split(" ,".ToArray(), StringSplitOptions.RemoveEmptyEntries);
since this happens a lot, I use the .ToArray() out of habit. You can also use a new construct (eg new char [] { ' ', ',' } ) I find that more cumbersome, but probably slightly faster.
simply split both the string within an array and them compare both the strings using contains() function.
string implements IEnumerable<char>, thus, you're intersecting sequences of characters instead of strings.
You should use String.Split:
IEnumerable<string> S1 = first.Substring(0, half).Split(' ');
IEnumerable<string> S2= first.Substring(half, half).Split(' ');
And then your intersection will output the desired result.
Also, you can convert each string representation of numbers into integers (i.e. int):
IEnumerable<int> S1 = first.Substring(0, half).Split(' ').Select(s => int.Parse(s));
IEnumerable<int> S2 = first.Substring(half, half).Split(' ').Select(s => int.Parse(s));
You are converting all your characters into integers. The character '1' is not represented by the integer 1. Change your foreach to:
foreach (char i in areInCommon)

Split a string containing various spaces

I have txt file as follows and would like to split them into double arrays
node Strain Axis Strain F P/S Sum Cur Moment
0 0.00000 0.00 0.0000 0 0 0 0 0.00
1 0.00041 -83.19 0.0002 2328 352 0 0 -0.80
2 0.00045 -56.91 0.0002 2329 352 0 0 1.45
3 0.00050 -42.09 0.0002 2327 353 0 0 -0.30
My goal is to have a series of arrays of each column. i.e.
node[] = {0,1,2,3), Axis[]= {0.00,-83.19,-56.91,-42.09}, ....
I know how to read the txt file and covert strings to double arrays. but the problem is the values are not separated by tab, but by different number of spaces. I googled to find out a way to do it. However, I couldn't find any. some discussed a way to do with a constant spaces. If you know how to do or there is an existing Q&A for this issue and let me know, it will be greatly appreciated. Thanks,
A different way, although I would suggest you stick with the other answers here using RemoveEmptyEntries would be to use a regular expression, but in this case it is overkill:
string[] elements = Regex.Split(s, #"\s+");
StringSplitOptions.RemoveEmptyEntires should do the trick:
var items = source.Split(new [] { " " }, StringSplitOptions.RemoveEmptyEntries);
The return value does not include array elements that contain an empty string
var doubles = text.Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Skip(1)
.Select(line => line.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)
.Select(x => double.Parse(x)).ToArray())
.ToArray();
Use the option StringSplitOptions.RemoveEmptyEntries to treat consecutive delimiters as one:
string[] parts = source.Split(' ',StringSplitOptions.RemoveEmptyEntries);
then parse from there:
double[] values = parts.Select(s => double.Parse(s)).ToArray();

How Can I read From Line number() to line Starts with in C#

Let's say I have text file like this
<pre>----------------
hPa m C
---------------------
1004.0 28 13.6
1000.0 62 16.2
998.0 79 17.2
992.0 131 18.0
<pre>----------------
Sometext here
1000.0 10 10.6
1000.0 10 11.2
900.0 10 12.2
900.0 100 13.0
<aaa>----------------
How Can I Create Array in C# that reads text file from line number 5 (1004.0) to just before line that starts with string <pre>-
I used string[] lines = System.IO.File.ReadAllLines(Filepath);
To make each line in the array
The problem is I want only numbers of first section in the array in order to separate them later to another 3 arrays (hPa, m, C) .
Here's a possible solution. It's probably way more complicated than it should be, but that should give you an idea of possible mechanisms to further refine your data.
string[] lines = System.IO.File.ReadAllLines("test.txt");
List<double> results = new List<double>();
foreach (var line in lines.Skip(4))
{
if (line.StartsWith("<pre>"))
break;
Regex numberReg = new Regex(#"\d+(\.\d){0,1}"); //will find any number ending in ".X" - it's primitive, and won't work for something like 0.01, but no such data showed up in your example
var result = numberReg.Matches(line).Cast<Match>().FirstOrDefault(); //use only the first number from each line. You could use Cast<Match>().Skip(1).FirstOrDefault to get the second, and so on...
if (result != null)
results.Add(Convert.ToDouble(result.Value, System.Globalization.CultureInfo.InvariantCulture)); //Note the use of InvariantCulture, otherwise you may need to worry about , or . in your numbers
}
Do you mean this?
System.IO.StreamReader file = new System.IO.StreamReader(FILE_PATH);
int skipLines = 5;
for (int i = 0; i < skipLines; i++)
{
file.ReadLine();
}
// Do what you want here.

c# reading text file into arrays [duplicate]

This question already has answers here:
2d Array from text file c# [closed]
(3 answers)
Closed 9 years ago.
How can I loop through a text file to create six arrays from the content of the text file.
For example, the text file will look like this but with more lines(without title) maybe 200 of them
top_speed average_speed cadence altitude heart_rate power
84 73 0 -124 0 50
86 179 84 -125 121 3893
It would be nice to have an array for each. So, for example
top_speed = 84 + 86 : average_speed = 73 + 179 ... (and so on)
What's the best way to do this?
Anyway, if that is homework, following code will not help you :) But if it is not homework, you will understand how to parse such files with LINQ
var items =
File.ReadAllLines(filename) // read lines from file
.Select(line => line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(Int32.Parse)
.ToArray()) // convert each line to array of integers
.Select(values => new {
TopSpeed = values[0],
AverageSpeed = values[1],
Cadence = values[2],
Altitude = values[3],
HeartRate = values[4],
Power = values[5]
}); // create anonymous object with nice strongly-typed properties
int[] topSpeeds = items.Select(i => i.TopSpeed).ToArray();
You could create a Record class and then use a simple LINQ query:
var records = File.ReadLines("file.txt")
.Select(line =>
{
string[] parts = line.Split('\t');
return new Record
{
TopSpeed = int.Parse(parts[0]),
AverageSpeed = int.Parse(parts[1]),
Cadence = int.Parse(parts[2]),
Altitude = int.Parse(parts[3]),
HeartRate = int.Parse(parts[4]),
Power = int.Parse(parts[5])
};
}).ToArray();
This will give you a bunch of Records, one per line in the original file. If you wanted to then check all of HeartRates for building a histogram or graphing or whatever, you could grab them like this:
var allHeartRates = records.Select(rec => rec.HeartRate);

Categories

Resources