I'm doing data involving arrays in C#, when I use the foreach loop it gave me an message
cannot convert type char to string
int[,] tel = new int[4, 8];
tel[0, 0] = 398;
tel[0, 1] = 3333;
tel[0, 2] = 2883;
tel[0, 3] = 17698;
tel[1, 0] = 1762;
tel[1, 1] = 176925;
tel[1, 2] = 398722;
tel[2, 0] = 38870;
tel[3, 1] = 30439;
foreach (string t in tel.ToString())
{
Console.WriteLine(tel +" " +"is calling");
Console.ReadKey();
}
That is becuase when you foreach over a string each value will be a char, but you are trying to cast them to string.
foreach(string t in tel.ToString())
But it's unlikely that you want to foreach on tel.ToString() as the will return the name of the type of tel (System.Int32[,]). Instead you probably want to iterate all the values in tel
for(int i=0; i<4; i++)
{
for(int j=0; j<8; j++)
{
Console.WriteLine(tel[i,j] +" is calling");
Console.ReadKey();
}
}
Or
foreach(int t in tel)
{
Console.WriteLine(t +" is calling");
Console.ReadKey();
}
Note that some of the values will be zero since you do not assign values to all the positions in the tel array.
Iterate over the values in the array like this:
int rowLength = tel.GetLength(0);
int colLength = tel.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.WriteLine(tel[i, j]+" is calling");
}
}
Console.ReadLine();
Related
I am trying to implement a step counter into my bubble sort algorithm, but I don't know how to display the counter at the end of the sorting algorithm. If anyone could explain how I should go about this that would be great. Thank You.
My current code: (Bubble Sort):
static int[] bubbleSort(int[] arr, int n)
{
int stepCount = 0; // <- Counter to return and display
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j + 1] < arr[j])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
stepCount++;
}
}
return arr;
}
public static void DisplayArrayBubble(int[] arr)
{
foreach (int i in arr)
{
Console.Write(i.ToString() + " ");
}
}
Why not just return int - number of steps? I.e.
// arr : will be sorted
// return : number of steps
static int bubbleSort(int[] arr) {
if (null == arr)
return 0;
int stepCount = 0;
for (int i = 0; i < arr.Length - 1; i++)
for (int j = 0; j < arr.Length - 1 - i; j++)
if (arr[j + 1] < arr[j]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
stepCount += 1;
}
return stepCount;
}
Demo:
int[] sample = new int[] {1, 5, 4, 3, 2, 7};
int steps = bubbleSort(sample);
Console.WriteLine($"Sorted [{string.Join(", ", sample)}] in {steps} steps");
Outcome:
Sorted [1, 2, 3, 4, 5, 7] in 6 steps
There a plethora of ways but one is to make a custom class to hold both pieces of information that you need:
public class BubbleObject
{
public int[] arr { get; set; }
public int stepCount { get; set; }
}
Then adjust the code you have to use that object:
static BubbleObject bubbleSort(int[] arr, int n)
{
int stepCount = 0;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j + 1] < arr[j])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
stepCount++;
}
}
BubbleObject bo = new BubbleObject() { arr=arr, stepCount=stepCount}
return bo;
}
public static void DisplayArrayBubble(BubbleObject bo)
{
Console.WriteLine("Number of Steps = " + bo.stepCount);
foreach (int i in bo.arr)
{
Console.Write(i.ToString() + " ");
}
}
That should do it. There are other ways as well.
So I ran into a problem, I have a big text in a TXT file and I need to read it into a multidimensional array, without using LINQ.
Example:
Hello(a11) my(a12) friend(a13).
My(a21) name(a22) is(a23) David(a24),
I(a31) am(a32) from(a33) England(a34).
What I have done so far:
String input = File.ReadAllText( "..\\..\\Analize.txt" );
int i = 0, j = 0;
string[,] result = new string[10, 10];
foreach (var row in input.Split('\n'))
{
j = 0;
foreach (var col in row.Trim().Split(' '))
{
result[i, j] = string(col.Trim());
j++;
}
i++;
}
For the others who said his code "works just fine - true if his text is not dynamic size - but if there are more lines then 10, or more words then 10 in this particular example there will be an IndexOutOfRangeException !
If you do know anything about your file this is maybe the best for not running into exceptions:
string[] lines = File.ReadAllLines("C:/temp/test.txt");
int sizex = lines.Length;
int sizey = 1;
for (int i = 0; i < lines.Length; i++)
{
var splitline = lines[i].Split(' ');
sizey = sizey < splitline.Length ? splitline.Length : sizey;
}
String[,] multillines = new string[sizex,sizey];
for (int i = 0; i < lines.Length; i++)
{
var splitline = lines[i].Split(' ');
for (int j = 0; j < splitline.Length; j++)
{
multillines[i, j] = splitline[j];
}
}
Your code as it is works just fine. Not sure what your problem is. But if this:
Hello(a11)
means that this word has to sit on position [1,1] then all you have to change is the counting start from 0 to 1
int i = 1, j = 1;
Try this:
String input ="Hello(a11) my(a12) friend(a13)";
int i = 0, j = 0;
int[,] result = new int[10, 10];
foreach (var row in input.Split(' '))
{
j = 0;
foreach (var col in row.Trim().Split(' '))
{
result[i, j] = int.Parse(col.Trim());
j++;
}
i++;
}
Console.WriteLine(result[3,9]);
this is the text file that i want to split into a 2D array
"YHOO",36.86,21,13873900,37.00
"GOOG",684.11,1114,1821650,686.72
"MSFT",50.54,3993,31910300,50.65
"AAPL",94.40,28201,39817000,94.26
and this is the code I have implemented to do this but it won't work
String input = File.ReadAllText(#"..\..\Data\stockInfo.txt");
int i = 0, j = 0;
string[,] result = new string[3, 5];
foreach (var row in input.Split('\n'))
{
j = 0;
foreach (var col in row.Trim().Split(','))
{
result[i, j] = string.Parse(col.Trim());
j++;
}
i++;
}
Jagged array String[][] (array of array) is often more flexible than 2D one String[,]:
string[][] result = File
.ReadLines(#"..\..\Data\stockInfo.txt")
.Select(line => line.Split(','))
.ToArray();
If you insist on 2D array you have to put less efficient code
string[] lines = File.ReadAllLines(#"..\..\Data\stockInfo.txt");
string[,] result = null;
for (int i = 0; i < lines.Count; ++i) {
string[] items = lines.Split(',');
if (null == result)
result = new string[lines.Count, items.Length];
for (int j = 0; j < items.Length; ++j)
result[i, j] = items[j];
}
The size of array was wrong. Also, you don't need to string.Parse, as output of Split is IEnumerable of strings
int i = 0, j = 0;
string[,] result = new string[4, 5];
foreach (var row in input.Split('\n'))
{
j = 0;
foreach (var col in row.Trim().Split(','))
{
result[i, j] = col.Trim();
j++;
}
i++;
}
My task is to migrate this Java code to a C# version, but I'm having trouble with the ValueOf method, since I can't seem to find a equivalent version for C# (because of the Radix parameter used on Java, 16 in this case).
public String decrypt_string(String s)
{
String s1 = "";
int i = s.length() / 2;
int[] ai = new int[i];
for (int j = 0; j < i; j++)
{
// This is the "problematic" line \/
ai[j] = Integer.valueOf(s.substring(j * 2, j * 2 + 2), 16).intValue();
}
int[] ai1 = decrypt_block(ai, i);
for (int k = 0; k < i; k++)
{
if (ai1[k] != 0)
s1 = s1 + (char)ai1[k];
}
return s1;
}
Here is my try, but it failed:
public String decrypt_string(String s)
{
String s1 = "";
int i = s.Length / 2;
int[] ai = new int[i];
for (int j = 0; j < i; j++)
{
int startIndex = j * 2;
string tmp = s.Substring(startIndex, 2);
ai[j] = Int32.Parse (tmp);
}
int[] ai1 = decrypt_block(ai, i);
for (int k = 0; k < i; k++)
{
if (ai1[k] != 0)
s1 = s1 + (char)ai1[k];
}
return s1;
}
Thanks in advance
If you are trying to parse a hexadecimal (base-16) number, use this:
int.Parse (tmp, NumberStyles.HexNumber);
You need to convert a string to an integer, given that the string is in a specific base.
int i = Convert.ToInt32(str, 16);
int j = Convert.ToInt32("A", 16); // 10
So:
for (int j = 0; j < i; j++)
{
int startIndex = j * 2;
ai[j] = Convert.ToInt32(s.Substring(startIndex, 2));
}
The radix is on Integer.valueOf(), not s.substring() in the java code you show there, so this would become:
ai[j] = Int32.Parse(s.Substring(j * 2, j * 2 + 2), 16);
I have this bit of code here:
int i = 0;
StreamReader re = File.OpenText("TextFile1.txt");
string input = null;
while ((input = re.ReadLine()) != null)
{
string[] sites = input.Split(' ');
for (int j = 0; j < sites.Length; j++)
{
MyArray[i, j] = Convert.ToInt32(sites[j]);
}
i++;
}
for (int a = 0; a < 5; a++)
{
for (int j = 0; j < 5; j++)
{
Console.Write(MyArray[a, j] + " ");
}
Console.WriteLine();
}
My problem is this line of code
MyArray[i, j] = Convert.ToInt32(sites[j]);
Its getting converted to an int, how do I convert it to a float?
Try float.Parse(string) or Double.Parse(string)
MyArray[i, j] = Convert.ToSingle(sites[j]);
Convert.ToSingle method or whole bunch of others.
EDIT:
Here's an related article: Double.TryParse or Double.Convert - what is faster and more safe? of interest in SO.