I have a problem at the line String fromIndexString = topStiva.Substring(topStivaLength + 1, topStiva.Length); . I shows that topStiva.Length is out or range.
The code is as follows:
String actiuneRezultata(String topStiva, String cuvIntr) {
int index = -1;
String primulCharCuvIntr = cuvIntr.Substring(0, 1);
if (primulCharCuvIntr.Equals("+") == true)
primulCharCuvIntr = "\\" + primulCharCuvIntr;
else
if (primulCharCuvIntr.Equals("*") == true)
primulCharCuvIntr = "\\" + primulCharCuvIntr;
else
if (primulCharCuvIntr.Equals("*") == true)
primulCharCuvIntr = "\\" + primulCharCuvIntr;
else
if (primulCharCuvIntr.Equals("*") == true)
primulCharCuvIntr = "\\" + primulCharCuvIntr;
else
if (primulCharCuvIntr.Equals("*") == true)
primulCharCuvIntr = "\\" + primulCharCuvIntr;
for (int i = 0; i < ta.Length; i++) {
if (ta[i].CompareTo(primulCharCuvIntr) == 0) {
index = i;
break;
}
}
int topStivaLength = topStiva.Length - 1;
while (topStiva[topStivaLength] >= '0' && topStiva[topStivaLength] <= 9)
topStivaLength--;
String fromIndexString = topStiva.Substring(topStivaLength + 1, topStiva.Length);
int fromIndex = int.Parse(fromIndexString);
if (index < 0)
return "Nu face parte din gramatica!";
else
return tabela[fromIndex][index];
}
The value topStiva is gets it from the call actiuneRezultata(stivaAPD.Peek().ToString(), another_value)
I saw that in stivaAPD I am geeting after push some values. So why is it that is out of range? Pls help!
The second argument to String.Substring is the length of the desired substring. You seem to be calling it as if it were instead the (exclusive) end index of the substring. Try calling the following so that your length is equal to the distance to the end index of the string.
topStiva.Substring(topStivaLength+1, topStiva.Length - (topStivaLength+1));
If topStivaLength is -1, this (topStiva[topStivaLength] will cause an exception.
If topStivaLength is 0 and topStiva is an empty string, this (topStiva[topStivaLength] will cause an exception.
Next time indicate exactly on what line you are getting the exception.
Related
This question already has answers here:
Remove last specific character in a string c#
(9 answers)
Closed 4 years ago.
Create a string function ReturnOdd(int [] tab, int i), which returns only odd numbers from an array using recursion, e.g 3,9,7,5,21,23
static ReturnOdd(int [] tab, int i)
{
if (tab.Length == 0 || i >= tab.Length)
return "";
if (i == tab.Length - 1)
{
if (tab[i] % 2 != 0)
return Convert.ToString(tab[i]);
else
return "";
}
if (tab[i] % 2 != 0)
return Convert.ToString(tab[i] + "," + ReturnOdd(tab, i + 1));
else
return Convert.ToString(ReturnOdd(tab, i + 1));
}
It's fine when the last value in array is odd, but when it's even funcion displays comma at the end of the lane e.g 1,5,765,3,675,55,811,
Could someone help me with getting rid of the comma at the end?
static string ReturnOdd(int[] tab, int i)
{
if (tab.Length == 0 || i >= tab.Length)
return "";
if (i == tab.Length - 1)
{
if (tab[i] % 2 != 0)
return Convert.ToString(tab[i]);
else
return "";
}
if (tab[i] % 2 != 0)
{
string s = ReturnOdd(tab, i + 1);
if (!String.IsNullOrEmpty(s))
s = "," + s;
return Convert.ToString(tab[i] + s);
}
else
return Convert.ToString(ReturnOdd(tab, i + 1));
}
I'd still do it like this:
static String ReturnOdd(int[] tab)
{
StringBuilder sb = new StringBuilder();
foreach (int i in tab)
{
if (i % 2 == 1)
sb.Append($"{i},");
}
return sb.ToString().TrimEnd(',');
}
You can check the string to see if it ends with a comma, and if it does, you can take a substring starting with the first character and taking all but the last one:
string s = "8,2,3,4,5,"; // just a sample - this would be your list of odd numbers
if (s.EndsWith(","))
s = s.Substring(0, s.Length - 1); // leave off the last character
I have below code:
String[] splititemcol;
String[] splititem;
String singlestring;
while (reader.Read())
{
splititemcol = reader.GetValue(2).ToString().Split((char)16); //split each item
for (int i = 0; i < splititemcol.Count(); i++)
{
splititem = splititemcol[i].ToString().Split((char)14);
resultstr.Append("<tr><td>" + splititem[0] + "</td><td>");
singlestring = "";
for(int k=0;k<splititem.Count();k++)
{
if(k==2)
{
singlestring = splititem[k].ToString();
break;
}
}
resultstr.Append(singlestring + "</td></tr>");
}
}
In above code I could get value of 3rd splititem.
String[] splititemcol;
String[] splititem;
String singlestring;
while (reader.Read())
{
splititemcol = reader.GetValue(2).ToString().Split((char)16); //split each item
for (int i = 0; i < splititemcol.Count(); i++)
{
splititem = splititemcol[i].ToString().Split((char)14);
resultstr.Append("<tr><td>" + splititem[0] + "</td><td>");
singlestring =splititem[2].ToString();
resultstr.Append(singlestring + "</td></tr>");
}
}
In above code I try to get value of 3rd splititem only by array index i.e. without foreach.
But it throws Index was outside the bounds error on line 9 as below.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array.
When I test splititem.Count it shows 4.
EDIT:
I manually store every value of the array in variable as like this and all are return values. So I come to the conclusion that either we have to iterate array by for loop or this script is stuck due to my strange delimiter in the strings (character 14).
String[] splititemcol;
String[] splititem;
String singlestring;
String item="";
String weight="";
String quantity="";
String amount="";
while (reader.Read())
{
splititemcol = reader.GetValue(2).ToString().Split((char)16); //split each item
for (int i = 0; i < splititemcol.Count(); i++)
{
splititem = splititemcol[i].ToString().Split((char)14);
resultstr.Append("<tr><td>" + splititem[0] + "</td><td>");
singlestring = "";
for(int k=0;k<splititem.Count();k++)
{
if (k == 0)
item = splititem[k].ToString();
else if (k == 1)
weight = splititem[k].ToString();
else if (k == 2)
quantity = splititem[k].ToString();
else if (k == 3)
amount = splititem[k].ToString();
}
resultstr.Append(weight + "</td><td>" + quantity + "</td><td>" + amount + "</td></tr>");
}
}
Thank you for all you guys try to give solution in this issue.
That means splititem[2] doesn't exists. In your first case you have the below condition which considering only lines which will have splititem[2] but in second case you are trying to access index 2 directly resulting in exception
if(k==2)
{
singlestring = splititem[k].ToString();
break;
}
Compare this (from first snippet):
if(k==2)
{
singlestring = splititem[k].ToString();
break;
}
with this (from the second snippet):
singlestring =splititem[2].ToString();
In the first case you make a check and provided that k==2 is true you read the corresponding value. That misses from the second case and nobody guarantees that splititem has a Length of 3.
I am making a code that decrements the line index in an array of strings. My array is like this:
1.ExampleFirst\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
2.ExampleSecond\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
and so on. The lengths of the lines are not the same.
I want the text to be like this:
0.ExampleFirst\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
1.ExampleSecond\n
SomeText\n
SomeOtherText\n
FinalLine\n\n
I have made this code:
int s = 0;
while(s < lineCounter.Count())
{
if (int.TryParse(lineCounter[s].Substring(0, 1), out v) == true && lineCounter[s] != "\n")
{
int m = int.Parse(lineCounter[s].Substring(0,1));
lineCounter[s].Remove(0, lineCounter[s].IndexOf(".")).Insert(0, (m - 1).ToString());
Console.WriteLine(lineCounter[s]);
}
else
Console.WriteLine(lineCounter[s]);
s++;
The "if" is executed only when the line contains the number and when the line is not a new line. The else is executed to write the other lines in the array.(I'm using console.writeLine to see the results. I know I have to change that part)
When I execute this code, I get the following exception in the "if" statement:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index and length must refer to a location within the string.
To me this means that "if" is executed even when the new line between the last line of the first text block and the first line of the second text block is encountered. I can't explain why. Help please!
Declaring dotIndex with combination of string.Remove() and string.Insert() may do the trick.
string[] lineCounter = new string[]{
"1.ExampleFirst\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n\n",
"2.ExampleSecond\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n\n"
};
for (int i = 0; i < lineCounter.Count(); ++i) {
int dotIndex = lineCounter[i].IndexOf('.');
if (dotIndex < 1) //must be at least in the position of 2 or above
continue;
int lineIndex = 0;
if (int.TryParse(lineCounter[i].Substring(0, dotIndex), out lineIndex)) { //if can be parsed
lineIndex--; //decrement lineIndex
lineCounter[i] = lineIndex.ToString() + lineCounter[i].Remove(0, dotIndex);
}
}
I prefer to use for-loop to make the loop more definite, but you could change that to while/do.
This works fine in my PC. Output:
Edit:
All the results should be in the lineCounter. If you want to see them along the function, you could do:
for (int i = 0; i < lineCounter.Count(); ++i) {
int dotIndex = lineCounter[i].IndexOf('.');
if (dotIndex < 1) { //must be at least in the position of 2 or above
//Print here
continue;
}
int lineIndex = 0;
if (int.TryParse(lineCounter[i].Substring(0, dotIndex), out lineIndex)) { //if can be parsed
lineIndex--; //decrement lineIndex
lineCounter[i] = lineIndex.ToString() + lineCounter[i].Remove(0, dotIndex);
}
//Print here also
}
you probably want this:
string[] lineCounter=new string[]{
"1.ExampleFirst\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n",
"\n",
"2.ExampleSecond\n",
" SomeText\n",
" SomeOtherText\n",
" FinalLine\n",
"\n"
};
int v = 0;
int s = 0;
while (s < lineCounter.Count())
{
if (int.TryParse(lineCounter[s].Substring(0, 1), out v) == true && lineCounter[s] != "\n")
{
int m = int.Parse(lineCounter[s].Substring(0, 1));
Console.WriteLine(lineCounter[s].Remove(0, lineCounter[s].IndexOf(".")).Insert(0, (m - 1).ToString()));
}
else
Console.WriteLine(lineCounter[s]);
s++;
}
I believe you may be having issues with empty lines on the string array.
Maybe something like this works for you.
IEnumerable<string> ShiftIndexes(IEnumerable<string> lines) {
foreach (string line in lines) {
if (!string.IsNullOrEmpty(line) && char.IsDigit(line, 0)) {
int dotPos = line.IndexOf('.');
int index = int.Parse(line.SubString(0, dotPos));
yield return (index - 1).ToString() + line.SubString(dotPos);
}
else
yield return line;
}
}
And then use it like this:
string[] shiftedLines = ShiftIndexes(originalLines).ToArray();
I.m using c# language .I have a dictionary. the key is string of peoples emails. The value for each key is a list of objects. Those objects has 2 dateTime variables start and End.
What I'm trying to do is finding when is the time that all people I have are free. in addition to finding the times if some of them are available.
I managed to solve the first part which when all users are available. However, since I'm using a linear search the code is really slow.
so my questions are:
What is the better algorithm for doing this kind of comparison, keep in mind I'm comparing date ranges.
What is the best way to find if some of them are available at a specific time ??
This is the method responsible for intersection
private static FreeTime Intersection(FreeTime first, FreeTime second)
{
Console.WriteLine("inside intersection " + first.Start + " "+ first.End + " sescond " + second.Start + " " + second.End);
int result1 = DateTime.Compare(first.Start, second.End);
int result2 = DateTime.Compare(first.End, second.Start);
int result3 = DateTime.Compare(first.Start, second.Start);
int result4 = DateTime.Compare(first.End, second.End);
Boolean equal = (result3 == 0 && result4 == 0);
if (!(result1 >= 0) && !(result2 <= 0) && !equal)
{
Console.WriteLine(new DateTime(Math.Max(first.Start.Ticks, second.Start.Ticks)).TimeOfDay + "min max" + new DateTime(Math.Min(first.End.Ticks, second.End.Ticks)).TimeOfDay);
return new FreeTime(new DateTime(Math.Max(first.Start.Ticks, second.Start.Ticks)), new DateTime(Math.Min(first.End.Ticks, second.End.Ticks)));
}
else if (result3 == 0 && result4 == 0)
return (new FreeTime(first.Start, first.End));
else return null;
This part is for iterating through the lists
foreach (var t in allFree)
{
if (allFree != null)///&& list.Count > 1)
{
Console.WriteLine(t.Start + " " + t.End + " in all freeeee");
foreach (var s in allFree)
{
if (!((DateTime.Compare(t.Start.Date, s.Start.Date) == 0) && (DateTime.Compare(t.Start, s.Start) == 0) && (DateTime.Compare(t.End, s.End) == 0)) && (t.Start.Date == s.Start.Date))
{
Console.WriteLine("callling inteersection 2 ");
intersection = Intersection(t, s);
}
// else if ((list.Count == list2.Count) && ((DateTime.Compare(t.Start.Date, s.Start.Date) == 0) && (DateTime.Compare(t.Start, s.Start) == 0) && (DateTime.Compare(t.End, s.End) == 0)) && (t.Start.Date == s.Start.Date))
// intersection = new FreeTime(t.Start, t.End);
if (intersection != null)
{
finalFree.Add(intersection);
Console.WriteLine(intersection.Start + " " + intersection.End + " intersection result");
intersecFound = true;
}
}//end foreach
if (!intersecFound)
{
// allFree.Add(t);
intersecFound = false;
}
I have made a email validation program in C#, but how do I check data outside of the string?
Here is my C# code:
private bool CheckEmail()
{
string email1 = email.Text;
//calculating the length of the email
int EmailLen = email1.Length;
int num = 0;
//the first character of the email must not be the "#"
if (email1.Substring(0, 1) != "#")
{
//checking the email entered after the first character as it is not a "#" so i will start from 1.
for (int i = 1; i < EmailLen; i++)
{
//prevents there from being two "#"next to each other
if (email1[i] == '#' && (i + 1) < email1.Length && email1[i + 1] != '#')
{
//if there is an "#" in the email then num will increase by one
num = num + 1;
//now the stored value of i is the position where the "#" is placed. j will be i+2 as there should be at least one character after the "#"
int j = i + 2;
if (j < EmailLen)
{
for (int k = j; k < EmailLen; k++)
{
//when it finds a "." In the email, the character after the "." Should not be empty or have a space, e.g. it should be something like ".com"
if (email1[k] == '.' && k + 1 < email1.Length && email1[k + 1] != ' ')
{
num = num + 1;
}
}
}
else
{
break;
}
}
}
}
else
{
num = 0;
}
//if the num is 2, then the email is valid, otherwise it is invalid. If the email had more than one "#" for example, the num will be greater than 2.
if (num == 2)
{
return true;
}
else
{
return false;
}
}
When I try typing in “aa#”, I get this error: “Index and length must refer to a location within the string.”
When I ty typing in aa#a. , I get this error: “Index and length must refer to a location within the string.”
You cannot access data outside of the string. This is for a very good reason - doing so would violate the type safety that is a major attraction of a virtual machine like the .NET CLR.
You just want to check your bounds to make sure you're not trying to access a part of the string that doesn't exist. BTW, for checking single characters, you totally want to be doing email1[i], not email1.Substring(i, 1), so you're not constructing new string objects left, right and center.
Your first test should be:
if (email1[i] == '#' && i + 1 < email1.Length && email1[i + 1] != '#')
Your problem is
email1.Substring(i + 1, 1)
On the last iteration of the for loop, i == EmailLen -1.
So i + 1 == EmailLen, which is one past the end of the string.