How to get command line arguments from position 1 - c#

Is there a way to get command line arguments in C# from args[1] and forward, excluding args[0]?
I've tried with this:
short argslenght = (short) args.Length;
string[] pargs = { "" };
for(int i = 1; i <= args.Length; i++)
{
pargs[i-1] = args[i];
}
But gives me this error:
System.IndexOutOfRangeException
Thanks for your time.

You are getting that error because you are trying to read a value from the array of index which exceeds the limit of the array length. It is happening for the last value. If there are 5 arguments, you can read the last one by args[4] but in your loop, you are trying to read it by args[5] which is causing the error.
You need to use Length -1 in your For loop, like this way:
for(int i = 1; i <= args.Length - 1; i++)
Or remove the = from the condition:
for(int i = 1; i < args.Length; i++)

Related

How can I skip loop for first and last element of array and set them to constant value?

I would like the loop to start from the second element and to end before the last one.
So that I can set the first and last one to constant value.
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
Console.Write($"A[{i},{j}] = ");
tab[i, j] = double.Parse(Console.ReadLine());
}
}
You can use LINQ simply:
var result = yourArray.Skip(1).SkipLast(1).Prepend(theConstValue)
.Append(theConstValue).ToArray();
The Prepend, Adds a value to the beginning of the sequence.
The Append, Appends a value to the end of the sequence.
Why don't do something like that?
for (int i = 1; i < n - 1; i++)
{
//your code
}
Let the loop start at element 1 and end it one earlier

c# split string in 2. letter by letter

I need split my string in 2, one letter to each variable.
Example: string = "ABCDEFGHIJ"
name1: ACEGI
name2: BDFHJ
I done so far:
var builderM = new StringBuilder();
var builderK = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
builderM.Append(s[i]);
builderK.Append(s[i++]);
}
txtM.Text = builderM.ToString();
txtK.Text = builderK.ToString();
But its showing same text in the 2.
you should use ++i instead of i++
for (int i = 0; i < s.Length; i++)
{
builderM.Append(s[i]);
if(i + 1 < s.Length) // to prevent IOR exception when count is odd.
builderK.Append(s[++i]); // pre increment.
}
the reason is that i++ is post incremented. that means i gets incremented after the expression therefor s[i++] will give you same item as s[i].
Another approach would be to use LINQ to filter odd and even indices into two strings, something like:
var even = new string(input.Where((c, idx) => idx % 2 == 0).ToArray());
var odd = new string(input.Where((c, idx) => idx % 2 != 0).ToArray());
If performance is not an issue, you can use LINQ:
var name1 = String.Join(String.Empty, str.Where((v, i) => i % 2 == 0));
var name2 = String.Join(String.Empty, str.Where((v, i) => i % 2 == 1));
You can also use the modulus operator (%) to determine if the index is even or odd, and put the even indexes in the first array and the odd indexes in the second one:
for (int i = 0; i < s.Length; i++)
{
if (i % 2 == 0) builderM.Append(s[i]);
else builderK.Append(s[i]);
}
If you'd rather increment the i inside the for body, you have to repeat the check against s.Length (as we do in the for condition). Also, you will need to either move the post-increment to the previous line (so that i is incremented in time), or use a pre-increment:
// Move post-increment to previous line example:
for (int i = 0; i < s.Length; i++)
{
builderM.Append(s[i++]);
if (i < s.Length) builderK.Append(s[i]);
}
// Use a pre-increment example:
for (int i = 0; i < s.Length; i++)
{
builderM.Append(s[i]);
if (++i < s.Length) builderK.Append(s[i]);
}

Can't get my array loop right

I'm getting an Index was outside the bounds of the array.
string[] paths = {
"\\\\server\\c$\\folder\\subfolder\\user1\\300\\1\\abc.docx",
"\\\\server\\c$\\folder\\subfolder\\user2\\400\\1\\xyz.docx",
};
FileInfo[] f = new FileInfo[paths.Length];
for (int i = 0; i <= paths.Length; i++)
{
f[i] = new FileInfo(paths[i]);
Console.WriteLine(f[i].Length);
}
I can't seem to figure out why, any ideas?
use < instead of <=
for (int i = 0; i < paths.Length; i++)
{
f[i] = new FileInfo(paths[i]);
Console.WriteLine(f[i].Length);
}
Arrays start counting itens from 0. So, if you have an array with length 2, your objects will be in position [0] and [1]. If you try to access the position [2], you'll get the Index was outside the bounds of the array exception, because index 2 doesn't exist in this array.
In your for loop, you're using <= paths.Length. Your paths length is 2. 2 is less or equals 2, so your code will be executed like this
f[2] = new FileInfo(paths[2]) //Position 2 doesn't exist
To solve this, just change from:
for (int i = 0; i <= paths.Length; i++)
To:
for (int i = 0; i < paths.Length; i++)
You have two items in your array
paths[0], paths[1]
Your looping over three items
paths[0], paths[1], paths[2]
To correct this, change
for (int i = 0; i <= paths.Length; i++)
to
for (int i = 0; i < paths.Length; i++)

How can i check if the specific strings exist in a List<string> and if not to remove the indexs from the List?

I tried this but this is not working.
I'm getting index out of bound exception.
for (int x = 0; x < newText.Count; x++)
{
for (int y = 0; y < WordsList.words.Length; y++)
{
if (!newText[x].Contains(WordsList.words[y]))
{
for (int n = 0; n < 3; n++)
newText.RemoveAt(x);
}
}
}
newText is a List
words is string[]
newText format is like this:
index 0 = this is a text hello all
index 1 = time&date (6/14/2014....)
index 2 = empty ""
index 3 = text hello world
index 4 = time&date (6/14/2014....)
index 5 = empty ""
And so on...
What i want to do is to loop over newText and if in index 0 there no any word(string) from words then remove index 0,1,2 next itertion check index 3 for any words if not exist one word or more remove indexs 3,4,5.
If in index 0 or 3 there is one word or more then do nothing dont remove anything.
In the end newText should be in the same format as before:
index 0 text line
index 1 date&time
index 2 empty ""
Just the new newText content will be with text lines that contain one ore more strings from words.
EDIT
This is what i tried now:
First this is how i build the List:
List<string> t = filterNumbers(text);
for (int i = 0; i < t.Count; i++)
{
if (!newText.Contains(t[i]))
{
newText.Add(t[i]);
newText.Add(dateTime[i]);
newText.Add("");
}
}
Removing numbers and leave only text and add it.
In the end in this case i have in newText 150 indexs. That's 50 indexs of text lines.
Then i tried this:
int lastindex = newText.Count - 1;
for (int i = newText.Count - 1; i >= 0; i--)
{
for (int x = 0; x < WordsList.words.Length; x++)
{
if (!newText[i].Contains(WordsList.words[x]))
{
if (i != lastindex)
{
newText.RemoveAt(i + 1);
}
newText.RemoveAt(i);
}
}
}
But i'm getting exception on the line:
if (!newText[i].Contains(WordsList.words[x]))
Index was out of range. Must be non-negative and less than the size of the collection
EDIT
If I understood correctly that you wanted to check whether a specific line contains some words and if not remove that and the two following lines, here is a possible solution:
// start at the bottom in the first line "that matters" and go down by 3
for (int x = newText.Count - 3; x >= 0; x-=3)
{
// check if the line contains any of the words specified
if (!WordsList.words.Any(w => newText[x].Contains(w)) || newText[x] == "")
{
// remove the checked line as well as the next two if not
l.RemoveRange(x, 3);
}
}
EDIT
Corrected the predicate to:
!WordsList.words.Any(w => newText[x].Contains(w));
from
!WordsList.words.Any(w => newText.Contains(w));
EDIT 2
Added the empty string as possibility
The problem was that if the line to test was empty, it would pass the test because it does not contain any word from WordsList.words. The test now includes the empty string as an option and removes it when encountered.
Looking at your logic:
(1) for (int i = newText.Count - 1; i >= 0; i--)
{
(2) for (int x = 0; x < WordsList.words.Length; x++)
{
if (...)
{
(3) newText.RemoveAt(i);
}
}
}
You can see that even if you removed lines in (3), you continue loop in (2) which can try again remove line in (2) for new indexes, which now become out of bounds
you need to add break after (3) to continue loop (1)
// For each 3-word-sets
for (int x = 0; x < newText.Count; x += 3)
{
// For each word in that 3-word-set
for (int k = x; k < 3; k++)
{
// Check each word
bool breakOut = false;
for (int y = 0; y < WordsList.words.Length; y++)
{
if (!newText[k].Contains(WordsList.words[y]))
{
newText.RemoveAt(x+2);
newText.RemoveAt(x+1);
newText.RemoveAt(x);
x -= 3;
breakOut = true;
break;
}
}
if (breakOut) { break; }
}
}
I just wanted to test and experiment with your original code. Haven't tested this. Just make sure the list contains 3×n items.
Ok, it seems your data structure is really bad. Anyway if you have to keep the structure as is I think this can work :
var newList = new List<string>();
for (int index = 0; index < newText.Count; index = index + 3)
{
if (WordsList.Any(t => newText[index].ToLower().Trim().Contains(t.ToLower().Trim())))
{
newList.AddRange(newText.Skip(index).Take(3));
}
}
newText = newList;

resolution of the following error?

private static void VisualizarAgendaOrdenada()
{
Pacientes.Sort();
for(int i = 0; i <= Pacientes.Count; i++)
{
var agenda = Agendas.Find(p => p.Paciente.Nome == Pacientes[i].Nome);
if (agenda != null)
{
Error,
"Index is out of bounds. Index cannot be negative or greater than the size of the collection."
Your loop condition is wrong: you may not loop until <= Pacientes.Count, but only until < Pacientes.Count.
for (int i = 0; i < Pacientes.Count; i++)
Otherwise you will try to access an index that is outside the range of the list. A list with Count elements is indexed from 0 to Count-1.
You're trying to read from the list under index which does not exist. Change your <= to <.
for(int i = 0; i < Pacientes.Count; i++)
Because arrays/lists are indexed starting from 0 when you need to iterate over all elements you always have to use < Count() or < Length.

Categories