IndexOutOfRangeException was unhandled- Index was outside the bounds of the array - c#

I have a for loop that adds items in an array to a listView.
(It'll grab items on a webpage, remove anything after the ' in the string, then add it to the listView)
The error I am getting is: IndexOutOfRangeException was unhandled- Index was outside the bounds of the array
Here's the code I am using:
string[] aa = getBetweenAll(vid, "<yt:statistics favoriteCount='0' viewCount='", "'/><yt:rating numDislikes='");
for (int i = 0; i < listView1.Items.Count; i++)
{
string input = aa[i];
int index = input.IndexOf("'");
if (index > 0)
input = input.Substring(0, index);
listView1.Items[i].SubItems.Add(input);
}
The error occurs on this line: string input = aa[i];
Anything I did wrong? How can I fix this issue so it'll stop happening? Thanks!
If you're wondering the code for the getBetweenAll method is:
private string[] getBetweenAll(string strSource, string strStart, string strEnd)
{
List<string> Matches = new List<string>();
for (int pos = strSource.IndexOf(strStart, 0),
end = pos >= 0 ? strSource.IndexOf(strEnd, pos) : -1;
pos >= 0 && end >= 0;
pos = strSource.IndexOf(strStart, end),
end = pos >= 0 ? strSource.IndexOf(strEnd, pos) : -1)
{
Matches.Add(strSource.Substring(pos + strStart.Length, end - (pos + strStart.Length)));
}
return Matches.ToArray();
}

Your looping the elements of 'listView1'
If the item count of listView1 exceeds the number of elements of the string array 'aa' you will get this error.
I would either change the loop to be
for( ..., i < aa.Length, ...)
or inside your for loop put an if statement to make sure that you are not exceeding the elements of aa. (although, I doubt this is what you want to do).
for (int i = 0; i < listView1.Items.Count; i++)
{
if( i < aa.Length)
{
string input = aa[i];
int index = input.IndexOf("'");
if (index > 0)
input = input.Substring(0, index);
listView1.Items[i].SubItems.Add(input);
}
}

Well it is simple, your ListView.Items.Count is bigger then aa.Length. You need to make sure they have the same size.

Your for loop should be changed to
for (int i = 0; i < aa.Length; i++)
Also, when you do the below line, make sure the index matches.
listView1.Items[i].SubItems.Add(input);
Because of your above error, it seems it does not match, You might be better off looping through your list view to find a matching ListView Item and then maniuplate it.

Related

Move an element from an array

How can I move an element from an index, for example to the front. Let's say this example : moving the second index to the front, and the rest of the elements remain the same. As I am working with algorithms I can't implement things like lists that I found most efficient I guess.
Example : 1 2 3 4
Output : 3 1 2 4
I assigned the value from the index to a temporary variable so far. But I do not know how to shift the elements, I'm guessing implementing somehow a for loop.
You have to change how you iterate based on whether your desired index is before or after the elements original index and handle those cases individually.
public static void MoveToIndex(int[] array, int from, int to)
{
if (array.Length < 2) return;
if (from == to) return;
if (from < 0 || array.Length <= from) throw new ArgumentException(nameof(from));
if (to < 0 || array.Length <= to) throw new ArgumentException(nameof(to));
var startIndex = Math.Min(from, to);
var endIndex = Math.Max(from, to);
var swappedValue = array[startIndex];
if (to < from)
{
array[startIndex] = array[endIndex];
}
for (var i = startIndex + 1; i <= endIndex; i++)
{
var current = array[i];
if (to < from)
{
array[i] = swappedValue;
swappedValue = current;
}
else
{
array[i - 1] = i == endIndex ? swappedValue : current;
}
}
}

Appending to StringBuilder while there is nothing left

I have to the task to rearrange the words in a sentence backwards, but i am able to do it only for the first letter.Example: Fun exam right.What i have until now:
var sentance = Console.Readline().Split(' ');
var rearrangedSentence = new StringBuilder();
for(int i = 0,i<sentance.Lenght,i++)
{
rearrangedSentence.Append(sentance[i].Last());//this gives me "nmt"
}
My question is how to make this loop repeat itself while there is nothing left.
Any help will be greatly appriciated :)
EDIT: Question is
I mean if i have the sentence "Fun exam right" the result should be :nmtuahFxgeir . We first take the last chars of each word append that results in "nmt" then take the next one and add them resulting in "nmtuah" and so on
When you use sentance[i].Last(), you are only picking up the last element of your array.
EDIT: As per your updated requirements, you can use this code.
//Get the sentence array
var sentence = Console.ReadLine().Split(' ');
var rearrangedSentence = new StringBuilder();
//Get the length of longest word in array
int loopLength = sentence.OrderBy(n => n.Length).Last().Length;
int x = 0;
// Run for the length of longest word
for (int i = loopLength-1; i >=0 ; i--)
{
// need to pick up an element at every run for each element.
for (var j = 0; j < sentence.Length; j++)
{
//Picking the position of item to be picked up
int val = sentence[j].Length - (x + 1);
// If index not out of bounds
if(val >= 0 && val <= sentence[j].Length)
{
// Pick the character and append to stringbuilder.
rearrangedSentence.Append(sentence[j][val]);
}
}
// Next letter should be n-1, then n-2.
// Increase this. Val will decrease
x++;
}
Console.WriteLine(rearrangedSentence.ToString());
Console.ReadLine();

How To Add Two List<> at run time ? Index out of range error My code Attached (ASP.net C#)

I am trying to add two lists in a loop by adding first index value of one list to the first index value of another list but both list are populating at run time after calculation issue is that how to track that list<> posses value at that index or not as shown below ,
Result[var]=first[var]+second[var]
complete code is give below,
List<double> Result = new List<double>();
for (int var = 0; var < 30; var++)
{
if (first[var] == null)
{
first[var] = 0;
}
if (second[var] == null)
{
second[var] = 0;
}
}
Result[var]=first[var]+second[var];
}
we do are not sure that both list may have value up to 10,15 .. index but i need if list one have 15 values and list two have 10 values then add two list in this way ,
A list[0]+B list[0]=
A list[1]+B list[1]=
A list[2]+B list[2]=
if it add
A list[11]+B list[11]=
then it add 0 from second list because it has only 10 values then how to validate b list[11] and use 0 if index 11 not exist in second list
one more thing list can have upto 30 values maximum not more then 30
You may need something like this (assuming that first and second are List):
List<double> Result = new List<double>();
for (int i = 0; i < 30; i++)
{
double firstVal = 0;
double secondVal = 0;
if (first.Count > i)
{
firstVal = first[i];
}
if (second.Count > i)
{
secondVal = second[i];
}
Result.Add(firstVal + secondVal);
}
If I understood correctly, you are trying to add two list values into another list. If one of the list is ended, consider the value as zero and continue till max available limit of either of the lists.
If so,
// assume i1, i2 are sources and i3 is result
int max = i1.Count>i2.Count?i1.Count:i2.Count;
for (int i = 0; i < max; i++)
{
i3[i] = (i1.Count > i ? i1[i] : 0) + (i2.Count > i ? i2[i] : 0);
}
// another varient:
for (int i = 0; i < i1.Count; i++)
{
i3[i] = i1[i] + (i2.Count > i ? i2[i] : 0);
}
for (int i = i1.Count; i < i2.Count; i++)
{
i3[i] = i2[i];
}

Setting the cursor's current line on a .NET TextBox

In .NET, you can easily get the line number of the cursor location of a TextBox (i.e. the "current line") by using GetLineFromCharIndex and SelectionStart:
var currentLine = textBox1.GetLineFromCharIndex(textBox1.SelectionStart);
Is there a "clean/native" way to set the cursor in a given line of a Textbox (i.e. set the "current line")? Or at least a "clean/native" way to get the char index of the first character of a given line (something like getCharIndexFromLine, the opposite of the function I put before)?
A way to do it would involve iterating over the first N-1 elements of the Lines property of the TextBox and summing their lengths plus the lengths of the linebreaks. Any other idea?
There is a GetFirstCharIndexFromLine() function that is available:
int myLine = 3;
int pos = textBox1.GetFirstCharIndexFromLine(myLine);
if (pos > -1) {
textBox1.Select(pos, 0);
}
This was the best I could come up with:
private void SetCursorLine(TextBox textBox, int line)
{
int seed = 0, pos = -1;
line -= 1;
if(line == 0) pos = 0;
else
for (int i = 0; i < line; i++)
{
pos = textBox.Text.IndexOf(Environment.NewLine, seed) + 2;
seed = pos;
}
if(pos != -1) textBox.Select(pos, 0);
}
If you want to start counting lines at 0 remove the line -= 1; segment.

1-Dimensional Array Counting Same Elements

I have a 1-dimensional array that fills up a table of 40 random elements (all the values are either 0 or 1). I want to find the longest consecutive span of values.
For example:
In 111100101 the longest row would be 1111 because it has four consecutive values of 1.
In 011100 the result is 111.
I have no idea how to check upon the "next element" and check if it's a 0 or 1.
Like the first would be 1111 (count 4) but the next would be a 0 value, meaning I have to stop counting.
My idea was placing this value (4) in a other array (example: 111100101), and place the value of the 1's back on zero. And start the process all over again.
To find the largest value I have made another method that checks up the biggest value in the array that keeps track of the count of 0's 1's, this is not the problem.
But I cannot find a way to fill the array tabelLdr up, having all the values of the group of elements of the same kind (being 0 or 1).
In the code below I have 2 if's and of course it will never go into the second if (to check if the next value in the array is != to its current state (being 0 or 1).
public void BerekenDeelrij(byte[] tabel, byte[] tabelLdr)
{
byte LdrNul = 0, Ldréén = 0;
//byte teller = 0;
for (byte i = 0; i < tabel.Length; i++)
{
if (tabel[i] == 0)
{
LdrNul++;
//this 2nd if cleary does not work, but i have no idea how to implend this sort of idea in my program.
if (tabel[i] == 1) //if value != 0 then the total value gets put in the second array tabelLdr,
{
tabelLdr[i] = LdrNul;
LdrNul = 0
}
}
if (tabel[i] == 1)
{
Ldréén++;
if (tabel[i] == 0)
{
tabelLdr[i] = Ldréén;
Ldréén = 0;
}
}
}/*for*/
}
This method should do what you need:
public int LargestSequence(byte[] array) {
byte? last = null;
int count = 0;
int largest = 0;
foreach (byte b in array) {
if (last == b)
++count;
else {
largest = Math.Max(largest, count);
last = b;
count = 1;
}
}
return Math.Max(largest, count);
}
Even while i is the loop counter, it is still just a variable. A valid for statement is for (;;), which is an infinite loop. Notice the for statement increments i, as in i++. The expression i = i + 1 works just as well.
Im unsure if you need the longest "row" of ones or longest row of either 0 or 1. This will work for the latter
var max = 0;
var start = 0;
var current = -1;
var count = 0;
for(int i = 0;i<table.Length;i++)
{
if(current = table[i])
{
count++;
}
else
{
current = table[i];
if(max < count)
{
max = count;
start = i-count;
}
count = 1;
}
}
if(max < count)
{
max = count;
start = i-count;
}
//max is the length of the row starting at start;

Categories

Resources