String array to int array conversion - c#

I have a problem with converting string array (previously loaded from .txt file) to integer one. File has got 100 random numbers, they load without any problem, I just need to convert them to integers to make them sortable with 3 types of sorting. I've tried many thing that were said here, but none of them seem to work. All the time I'm getting an error saying that it can't be converted.
Here is my loading from the file code:
string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();
int[] numb= new int[path.Length];
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
And after some options to choose I'm using switch to pick one:
switch (a)
{
case 1:
Console.WriteLine("1. Bubble.");
//int[] tab = numb;
babel(path);
for (int z = 0; z < path.Length; z++)
{
Console.Write(path[z] + ", ");
}
break;
I've got bubble sorting method in my program too, don't think it is necessary to post it here.
If anyone can help me here, I'd be really grateful.
#Amy - I've tried this:
numb[i] = path[i].Convert.toInt32(); - it doesn't work.
What I want to achieve is to change every number in this array to int, I think it should be involved here:
{
Console.WriteLine(path[i]);
}

This conversion works.
#string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();
String[] path = {"1","2","3"};
int[] numb = Array.ConvertAll(path,int.Parse);
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
for (int i = 0; i < numb.Length; i++)
{
Console.WriteLine(numb[i]);
}

It is better to use TryParse instead of parse. Also it is easier to work with List, than with array.
using System;
using System.Collections.Generic;
namespace StringToInt
{
class Program
{
static void Main(string[] args)
{
String[] path = { "1", "2", "3", "a", "b7" };
List<int> numb = new List<int>();
foreach (string p in path)
{
if (int.TryParse(p, out int result))
{
numb.Add(result);
}
}
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
for (int i = 0; i < numb.Count; i++)
{
Console.WriteLine(numb[i]);
}
}
}
}

I can't imagine this wouldn't work:
string[] path = File.ReadAllLines("C:\\Users\\M\\numb.txt");
int[] numb = new int[path.Length];
for (int i = 0; i < path.Length; i++)
{
numb[i] = int.Parse(path[i]);
}
I think your issue is that you are using File.ReadLines, which reads each line into a single string. Strings have no such ToArray function.

Related

Sort by selection in C#

I am a complete beginner in programming. Trying to make sorting a choice. Everything seems to be ok. Only there is one caveat. Only numbers up to 24 index are filled in the new array. I can’t understand what the problem is.
int[] Fillin(int[] mass)
{
Random r = new Random();
for(int i = 0; i < mass.Length; i++)
{
mass[i] = r.Next(1, 101);
}
return mass;
}
int SearchSmall(int[] mass)
{
int smallest = mass[0];
int small_index = 0;
for(int i = 1; i < mass.Length; i++)
{
if (mass[i] < smallest)
{
smallest = mass[i];
small_index = i;
}
}
return small_index;
}
int[] Remove(int[] massiv,int remind)
{
List<int> tmp = new List<int>(massiv);
tmp.RemoveAt(remind);
massiv = tmp.ToArray();
return massiv;
}
public int[] SortMass(int[] mass)
{
mass = Fillin(mass);
Print(mass);
Console.WriteLine("________________________________");
int[] newmass = new int[mass.Length];
int small;
for(int i = 0; i < mass.Length; i++)
{
small = SearchSmall(mass);
newmass[i] = mass[small];
mass = Remove(mass, small);
}
return newmass;
}
I think your main issue is that when you remove an element in the Remove function, the main loop in for (int i = 0; i < mass.Length; i++) will not check all elements o the initial array. A simple (and ugly) way to fix that would be not to remove the elements but to assign a very high value
public static int[] Remove(int[] massiv, int remind)
{
massiv[remind] = 999999;
return massiv;
}
Or as Legacy suggested simply modify the mass.length for newmass.lengh in the main loop.
As some others have mentioned this is not the best way to order an array, but it is an interesting exercise.

Selection Sort Implementation

I'm not really sure what's wrong with the implementation I have. How would I fix this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SelectionSort
{
class Program
{
static void algorithm(int[] to_sort)
{
int bufor;
for (int i = 0; i < to_sort.Length; i++)
{
for (int j = i + 1; j < to_sort.Length; j++)
{
if (to_sort[i] >= to_sort[j])
{
bufor = to_sort[i];
to_sort[i] = to_sort[j];
to_sort[j] = bufor;
}
}
}
}
static void Main(string[] args)
{
int[] to_sort = new int[100];
Console.WriteLine("");
for (int i = 1; i < 100; i++)
{
Console.Write(to_sort[i] + " ");
}
Console.WriteLine("");
algorithm(to_sort);
Console.WriteLine("\n");
Console.WriteLine("Sorted list:");
for (int i = 0; i < 100; i++)
{
Console.Write(to_sort[i] + " ");
}
Console.Read();
}
}
}
This produces the following output:
Original list: 00000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000
Sorted list: 000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000
It looks like my array (int[] to_sort) was empty, am I right? How can I get this:
Original list: 123456789....100
Sorted list: 123456789...100
Perhaps you originate from the C++ world where initializing an array does not mean the array is "cleaned" (the data that happened to be located at the allocated memory remains untouched), but in C# if you initialize an array like:
int[] to_sort = new int[100];
It means you construct an array where every element is set to default(T) with T the type. For an int that is 0 (for objects it is null, etc.). So you just constructed an array filled with zeros.
You can however for instance fill it with random numbers like:
Random rand = new Random();
for(int i = 0; i < to_sort.Length; i++) {
to_sort[i] = rand.Next(0,1000);
}
EDIT
Based on your comment, you want to fill it with the positions, you can do this like:
for(int i = 0; i < to_sort.Length; i++) {
to_sort[i] = i+1;
}
I think the easiest and shortest way you can initialize an array of sequential numbers is like this:
int[] to_sort = Enumerable.Range(1, 100).ToArray();
What you have will just allocate the array and fill it with the default value for int, which is 0:
int[] to_sort = new int[100];

Converting a 2d array along with its elements from string to int

As much as I tried to find a similar version in the question here, I couldn't find something.. so I am asking your help.
After reading some numbers from a textfile (now in string format), I split them in rows and columns and add them to a 2d-array (in string format as well). Now I want to convert everythinh in integers so that I can play with sorting the numbers out later.
Here is my code...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ArrayProgram
{
class Program
{
int number = 0;
int i = 0;
int k = 0;
string strnum;
public void onetohundredints()
{
StreamWriter writer = new StreamWriter("numberstored.txt");
for (i = 0; i < 10; i++)
{
for (k = 0; k < 10; k++)
{
number++;
Console.Write(number + " ");
strnum = number.ToString();
writer.Write(strnum + " ");
}
Console.WriteLine();
writer.WriteLine();
}
writer.Close();
}
public void readints()
{
StreamReader reader = new StreamReader("numberstored.txt");
string data = reader.ReadToEnd();
reader.Close();
string[,] dataarray = new string[10,10];
int[] numbers = new int[100];
string[] dataperlines = data.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<=dataperlines.Count()-1; i++)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j=0; j<=numbersperrow.Count()-1; j++)
{
dataarray[i, j] = numbersperrow[j];
}
}
}
public static void Main(string[] args)
{
Program prog = new Program();
prog.onetohundredints();
prog.readints();
Console.ReadKey();
}
}
}
After I insert the number into the 2d-array, how do I convert all of it in integers?
If you don't have a particular reason to have an array of strings, you can just save you data as int in the first place. Just change your inner for loop to do:
var parsed = int.TryParse(numbersperrow[j], out dataarray[i, j]);
if (!parsed)
{
// Error
}
While that should work, I would suggest to re-write your ReadData method to look similar to the sample below.
public int[,] ReadData(string filePath, int xDimension, int yDimension)
{
var results = new int[xDimension, yDimension];
var lines = File.ReadLines(filePath);
for (var i = 0; i < allLines.Count(); i++)
{
var values = lines[i].Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
for (var j = 0; j < values.Count(); j++)
{
var parsed = int.TryParse(values[j], out results[i, j]);
if (!parsed) { }
}
}
return results;
}
You're putting everything into a string array. That array can only hold strings, not numbers. If you want to make the 2d array hold numbers, define it as int[,] dataarray = new int[10,10]; Next, in the final loop, simply do dataarray[i, j] = Convert.ToInt32(numbersperrow[j]);
Edit: You can use int.TryParse(numbersperrow[j], out value) if you aren't sure that numbersperrow[j] will be a number. Value will return false if the conversion is not successful.
I am happy to say that both solutions work. I now have my numbers in my 2d array. But now I wish to play with them. Let's say that I want the numbers printed on the screen in reverse order.
Having this correct solution:
int numbers;
int[,] dataarray = new int[10,10];
string[] dataperlines = data.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<=dataperlines.Count()-1; i++)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j=0; j<=numbersperrow.Count()-1; j++)
{
numbers = int.Parse(numbersperrow[j]);
dataarray[i, j] = numbers;
Console.Write(numbers + " ");
}
Console.WriteLine();
}
I know that I have to make a double for loop. But how do I write a succesful syntax for the numbers to be printed properly?
I also tried this:
int[,] reversedarray = new int[10, 10];
reversedarray[i, j] = Array.Reverse(dataarray[i,j]);
but the dataarray[i,j] becomes red and the error "cannot convert from int to system.Array occurs... what am I missing?
I also tried this...
for (i = 10; i <= dataperlines.Count(); i--)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (j =10; j <= numbersperrow.Count(); j--)
{
numbers = int.Parse(numbersperrow[j]);
reversedarray[i, j] = numbers;
Console.Write(numbers + " ");
}
Console.WriteLine();
}
But I have an IndexOutOfRange exception coming from
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
I understood that since I splitted the columns into rows too, it is unecessary to write it again, but I am stuck. I tried simplifying the code since I have my 2darray with its elements and I my tries were fallacious. Any more suggestions?

(jagged array) Array of an Array: automatically create in while loop, how to initialize?

I would like to create an array of an array from a text file...
There are 20000 line with 21 strings in each line separated by ',' .
I would like to read each line and make it into an array , each line being a new array within.
So I wanted to create the jagged array by starting it like this:
string[][] SqlArray = new string[200000][21];
But it gives: ERROR MESSAGE : Invalid rank specifier: expected ',' or ]
How would I create this array or initialize it?
I will be populating the data in the array like this:
while (true)
{
string theline = readIn.ReadLine();
if (theline == null) break;
string[] workingArray = theline.Split(',');
for (int i = 0; i < workingArray.Length; i++)
{
for (int k = 0; k < 20; k++)
{
SqlArray[i][k] = workingArray[k];
}
}
}
Thank you
That type of initialization only works in Java. You must declare an array of arrays then initialize each in a loop.
string[][] SqlArray = new string[21][];
for(int index = 0; index < SqlArray.Length; index++)
{
SqlArray[index] = new string[2000000];
}
Alternatively, you can use a non-jagged array. It will probably work for what you need.
string[,] SqlArray = new string[21 , 2000000];
It can be accessed like so:
SqlArray[2,6264] = x;
To anyone who is interested this is how I ended up implementing it:
TextReader readIn = File.OpenText("..\\..\\datafile.txt");
string[][] SqlArray = new string[rowNumCreate][];
int e = 0;
while (true)
{
string theline = readIn.ReadLine();
if (theline == null) break;
string[] workingArray = theline.Split(',');
SqlArray[e] = new string[valuesInRow +1];
for (int k = 0; k < workingArray.Length; k++)
{
SqlArray[e][k] = workingArray[k];
}
e++;
}
The file being read is a simple mock database set as a flat file that was auto-generated to test an algorithm that I am implementing, which works with jagged arrays; hence instead of working with a data base I just created this for ease of use and to increase and decrease size at will.
Here is the code to build the text file:
Random skill_id;
skill_id = new Random();
// int counter =0;
string seedvalue = TicksToString();
int rowNumCreate = 200000;
int valuesInRow = 20;
string lineInFile = seedvalue;
string delimiter = ",";
for (int i = 0; i < rowNumCreate; i++)
{
for (int t = 0; t < valuesInRow; t++)
{
int skill = skill_id.Next(40);
string SCon = Convert.ToString(skill);
lineInFile += delimiter + SCon;
}
if (rowNumCreate >= i + 1)
{
dataFile.WriteLine(lineInFile);
lineInFile = "";
string userPK = TicksToString();
lineInFile += userPK;
}
}
dataFile.Close();
public static string TicksToString()
{
long ms = DateTime.Now.Second;
long ms2 = DateTime.Now.Millisecond;
Random seeds;
seeds = new Random();
int ran = seeds.GetHashCode();
return string.Format("{0:X}{1:X}{2:X}", ms, ms2, ran).ToLower();
}
I am still a student so not sure if the code is A-grade but it works :)

Simple program not working

this is the first time i work on C# and ASP.NET, i'm reading Beginning ASP.NET 4 in c# 2010 but i never worked with object-oriented programming. (I'm a network admin so i know basic programming).
Still, i can't get to work a simple program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2 {
class Program {
static void Main(string[] args) {
int i;
string[] nomi = new string[7];
string[] cognomi = new string[7];
for (i = 0; i = 6; i++) {
Console.WriteLine("Inserisci il", i + 1, "° nome");
nomi[i] = (Console.ReadLine);
}
for (i = 0; i = 6; i++) {
Console.WriteLine("Inserisci il", i + 1, "° cognome");
nomi[i] = (Console.ReadLine);
}
for (i = 0; i = 6; i++) {
Console.WriteLine(nomi[i], " ", cognomi[i]);
}
}
}
}
The problem is not in the algorythm but in the declaration part. I can't show the error log because i have VS in Italian.
Where am i wrong?
It's tough to help without error messages (maybe you can translate them since you obviously know both languages).
For sure, your for loop syntax is incorrect. This:
for (i = 0; i = 6; i++)
Should be:
for (i = 0; i < 6; i++) // Or <=, or whatever
Take a look at for loop documentation on MSDN.
In addition Console.ReadLine is a method, not a property:
nomi[i] = Console.ReadLine();
Your for loops are incorrect. They should be
for (int i = 0; i < 7; i++)
{
}
Or, better,
for (int i = 0; i < nomi.Length; i++)
{
}
What this is saying is that i should start at 0, continue looping until the value if i is no longer less than 7 (or the value of nomi.Length) and i should increase by 1 each loop (i++).
Also, unrelated to the loops, it should be Console.ReadLine();. The () shows that it's a method that takes no parameters, whereas nomi.Length does not have () because it is a property, not a method.
Your arrays also need to be static.
static string[] nomi = new string[7];
static string[] cognomi = new string[7];
Just to clarify, you don't always need to use static when declaring variables. The reason you need it here is because you're calling them from within a static method (static void Main(string[] args)).
Edit - As mentioned in the comments, this assumes that the variables are being declated outside the Main method which is resulting in the error An object reference is required for the nonstatic field, method, or property 'member'. If they are not, then these variables do not have to be static.
Your for loops don't make any sense for (i = 0; i = 6; i++)
The syntax is for (initialization, condition, iteration)
Right now your condition is an assignment, so it is always going to be true. I think you wanted it to be for (i = 0; i **<** 6; i++)
When writing for loops you should always make a int variable in the scope of the declaration of the for loop
Example:
for (int i = 0; i < 10; i++)
{
body code goes here
}
There integer should be declared and disappear within the scope of the loop.
Hope that helps
I corrected your for and Console.WriteLine syntax and made your code more readable. This should be able to guide you.
const int length = 7;
string[] nomi = new string[length];
string[] cognomi = new string[length];
for (int i = 0; i < length; i++)
{
Console.WriteLine("Inserisci il {0} ° nome", i + 1);
nomi[i] = (Console.ReadLine());
}
for (int i = 0; i < length; i++)
{
Console.WriteLine("Inserisci il {0} ° cognome", i + 1);
cognomi[i] = (Console.ReadLine());
}
for (int i = 0; i < length; i++)
{
Console.WriteLine("nomi: {0} cogomi: {1}", nomi[i], cognomi[i]);
}

Categories