Check next loop iteration data unless at end of loop c# - c#

I'm making a program which is creating an ASCII image. Based on the asterix input it produces different things. To start I'm making a basic outline however I have an issue where I cannot add something when checking last for loop iteration.
Method code:
private List<string> DrawOutline(List<string> inputLines)
{
List<string> output = new List<string>();
int door = r.Next(0, inputLines.Last().Length);
for (int li = 0; li < inputLines.Count; li++)
{
char[] curLine = inputLines[li].ToCharArray();
string outputLine1 = string.Empty;
string outputLine2 = string.Empty;
for (int i = 0; i < curLine.Length -1; i++)
{
Console.WriteLine(curLine[i]);
if (curLine[i] == '*')
{
outputLine1 += "+---";
outputLine2 += "| ";
}
else
{
outputLine1 += " ";
outputLine2 += " ";
}
if(li < curLine.Length - 1)
{
if (curLine[i] == '*' && curLine[i + 1] != '*')
{
outputLine1 += "+";
outputLine2 += "|";
}
}
}
output.Add(outputLine1);
output.Add(outputLine2);
}
return output;
}
When I run this, it works fine however will not add '+' and '|' to the last line of outputLines. This is because the line :
if(li < curLine.Length -1)
However without the -1 it will throw an exception because I am using [i+1] to decide something. Is there a way to check only if it won't throw an exception?

you can check if the end of the array has been reached by using the OR ( || ) statement. If the first statement of the OR statement returns true, the second is not checked. This is called short-circuiting. No error should be thrown in this case.
private List<string> DrawOutline(List<string> inputLines)
{
List<string> output = new List<string>();
int door = r.Next(0, inputLines.Last().Length);
for (int li = 0; li < inputLines.Count; li++)
{
char[] curLine = inputLines[li].ToCharArray();
string outputLine1 = string.Empty;
string outputLine2 = string.Empty;
for (int i = 0; i < curLine.Length -1; i++)
{
Console.WriteLine(curLine[i]);
if (curLine[i] == '*')
{
outputLine1 += "+---";
outputLine2 += "| ";
}
else
{
outputLine1 += " ";
outputLine2 += " ";
}
if (curLine[i] == '*' && (curLine.Length == i+1 || curLine[i + 1] != '*'))
{
outputLine1 += "+";
outputLine2 += "|";
}
}
output.Add(outputLine1);
output.Add(outputLine2);
}
return output;
}

Change if (li < curLine.Length - 1) to if (i < curLine.Length - 1)

Related

Unable to find long string in array string - C#

I'm trying to find a long string in another string. For this I've been using G[i].Contains(P[arr]) but for some reason the code just skips that condition. In my case : G[I] is 1000 character long and P[arr] is 475. When I debug I can see strings are not trimmed and also I have verified that P[ARR] is part of G[I] in Notepad++ so it should definitely satisfy a condition.
for (int arr = 0; arr < P.Length; arr++)
{
for (int i = a; i < G.Length; i++)
{
if (G[i].Contains(P[arr]))
{
if (!(b == 0))
{
a = i + 1;
continue;
}
primary_1 = (a == 0) ? G[i].IndexOf(P[arr]) : primary;
++count;
a = i + 1;
Console.WriteLine("Counter: " + i);
break;
}
}
}

how to store listbox values in a string variable in c#

I want to store all listbox control values in a string with "," separated so that I can show it in the label. I'm using for loop but giving error
for (int i = 0; i < ListBox2.Items.Count; i++){
if (ListBox2.Items[i].Selected == true || ListBox2.Items.Count > 0){
string projectnames += ListBox2.Items[i].ToString();
}
}
string projectnames = "";
bool firstValue = true;
for (int i = 0; i < ListBox2.Items.Count; i++)
{
if (ListBox2.Items[i].Selected == true || ListBox2.Items.Count > 0)
{
if(!firstValue)
{
projectnames += ", " + ListBox2.Items[i].ToString();
}
else
{
projectnames += ListBox2.Items[i].ToString();
firstValue = false;
}
}
}
Instead of the loop i'd use LINQ + String.Join:
var selected = ListBox2.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.ToString());
string projectnames = String.Join(",", selected);
On that way it's much better to read and you don't need to care about trailing commas.
This will generate a string of all selected items in the list.
string projectnames = "";
for (int i = 0; i < ListBox2.Items.Count; i++)
{
if (ListBox2.Items[i].Selected)
{
projectnames += ListBox2.Items[i].ToString() + ", ";
}
}
The most succinct method I can think of is:
var label = string.Join(",", listBox2.Items.Cast<string>());
(This uses System.Linq)
Try this, will help you!
protected void btnSave_Click(object sender, EventArgs e)
{
string selectedItem=string.Empty;
if (ListBox1.Items.Count > 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
selectedItem += ListBox1.Items[i].Text.ToString() + ", ";
//insert command
}
}
}
}

alternative method of creating string from list

Have such function, which creates string from List of ids
I try to run it in 50 threads, and after 30 seconds it hangs app
public string genText(List<string> list)
{
string text = #"{""text"":""";
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text += "!" + " ";
else
text += "!" + #""", ";
}
text += #"""start"":[";
for (int i = 0, lim = -2; i < list.Count; i++)
{
lim += 2;
if (i < list.Count - 1)
text += #"""" + lim + #""",";
else
text += #"""" + lim + #"""], ";
}
text += #"""end"":[";
for (int i = 1, lim = -1; i < list.Count + 1; i++)
{
lim += 2;
if (i < list.Count)
text += #"""" + lim + #""",";
else
text += #"""" + lim + #"""], ";
}
text += #"""type"":[";
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text += #"""USER"",";
else
text += #"""USER""], ";
}
text += #"""objectId"":[";
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text += #"""" + list[i] + #""",";
else
text += #"""" + list[i] + #"""]}";
}
return text;
}
What i­­­­­­­­­­­­­­s the best (alternative) way of writing such functio­­­­­­­­­­­­­­­­­­­­­­­n?
Expected result: {"text":"! ! ! ! ! ! ! ! ! ! ! ! ! ! !", "start":["0","2","4","6","8","10","12","14","16","18","20","22","24","26","28"], "end":["1","3","5","7","9","11","13","15","17","19","21","23","25","27","29"], "type":["USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER","USER"], "objectId":["524231066205","363249609235","509321690322","551832845250","273337925148","553378679618","552270073142","256641407","545454406232","548096729194","555315805314","553271555117","573655339037","518779453704","486606264340"]}
Instead of concatenating strings it is much more efficient to use the StringBuilder class.
public string genText(List<string> list)
{
StringBuilder text = new StringBuilder();
text.Append(#"{""text"":""");
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count - 1)
text.Append("!" + " ");
...
return text.ToString();
}
but as other have mentioned in the comments, use a Json library if you want to create Json data.

StackOverflow exception in a recursive method

I've written a recursive method in C# that should indent strings. For example, this string:
for (int i = 0; i < sb.Length; i++)
{
if (sb[i] == '{')
{
startIndex = i;
break;
}
}
should be converted to:
for (int i = 0; i < sb.Length; i++)
{
if (sb[i] == '{')
{
startIndex = i;
break;
}
}
My method is (updated):
private static string IndentText(string t,bool first = true)
{
if (first == false)
{
t = t.PadLeft(2);
}
int startIndex = t.IndexOf('{') + 1;
int stopIndex = t.LastIndexOf('}') - 1;
int blockLength = stopIndex - startIndex + 1;
if (blockLength <= 1 )
{
return "";
}
string start = t.Substring(0, startIndex);
string end = t.Substring(stopIndex + 1);
string indentBlock = t.Substring(startIndex, blockLength);
if (!CheckNestedBlocks(indentBlock))
{
return indentBlock;
}
return start + IndentText(indentBlock,false) + end;
}
private static bool CheckNestedBlocks(string t)
{
for (int i = 0; i < t.Length; i++)
{
if (t[i] == '{') // { and } always come in pairs, so I can check of only one of then
{
return true;
}
}
return false;
}
But I'm getting a StackOverflow exception in mscorlib.dll
What is my mistake? Thanks in advance.
By the way, because I think I'm complicating this problem, is there a better (and working) way to indent strings like this?
You should not include the braces in the "block" that is passed in the recursive call:
if (t[i] == '{')
{
startIndex = i + 1; // Start one character beyond {
break;
}
// ...
if (t[i] == '}')
{
stopIndex = i - 1; // Stop one character prior to }
break;
}

C# How to exclude an int from an array?

So I've got an array of integer. I want to use a loop and exclude integers that makes the equation true. So that would be like
for (int n = 0; n < first9char.Length; n++ ) {
if (first9char[n] == clickValue) {
first9char[n] = first9char[n + 1];
But then it only changes the value that is equal to not changing whole array. So is there any way to do this?
I want to use it in this loop.
if (UserSquareMethod.clickedBoxes[0] == -1) {
MessageBox.Show("You have not selected any box");
} else {
int i = 0;
do {
if (textButtonArray[clickedBox[i]].Text == "" || clickValue == "") {
textButtonArray[clickedBox[i]].Text = clickValue;
textButtonArray[clickedBox[i]].Font = new Font(textButtonArray[clickedBox[i]].Font.FontFamily, 14, FontStyle.Bold);
}
else
{
textButtonArray[clickedBox[i]].Text += "," + clickValue;
textButtonArray[clickedBox[i]].Font = new Font(textButtonArray[clickedBox[i]].Font.FontFamily, 5, FontStyle.Regular);
string[] first9char = textButtonArray[clickedBox[i]].Text.Split(new string[] { "," }, StringSplitOptions.None);
for (int j = 1; j < first9char.Length; j++)
{
for (int k = j - 1; k >= 0; k--)
{
if (first9char[j] == first9char[k])
{
if (clearNumberClicked == true)
{
first9char = Array.FindAll(first9char, x => x != clickValue);
label2.Text = first9char[0];
//int n = 0;
//for (int p = 0; p < first9char.Length; p++)
//{
// if (first9char[p] != clickValue)
// {
// first9char[n] = first9char[p];
// n++;
// label2.Text += "," + first9char[n];
// }
// }
//for (int n = 0; n < first9char.Length; n++ ) {
//if (first9char[n] == clickValue) {
// first9char[n] = first9char[n + 1];
// for ( int p = 0; p < n; p++) {
//}
//}
//}
MessageBox.Show("Clear the number" + first9char[(first9char.Length - 1)] + "and " + clickValue + " " + first9char.Length);
}
else {
first9char[j] = "";
textButtonArray[clickedBox[i]].Text = first9char[0];
MessageBox.Show("You cannot enter the same number again!"+ first9char[j]+j);
for (int m = 1; m < (first9char.Length - 1); m++) {
textButtonArray[clickedBox[i]].Text += ","+ first9char[m];
}
}
}
}
}
if (textButtonArray[clickedBox[i]].Text.Length > 9)
{
textButtonArray[clickedBox[i]].Text = first9char[0] + "," + first9char[1] + "," + first9char[2] + "," + first9char[3] + "," + first9char[4];
MessageBox.Show("You cannot enter more than 5 numbers, please clear the box if you want to enter different number." + textButtonArray[clickedBox[i]].Text.Length);
}
}
i++;
}
while (clickedBox[i] != -1);
}
}
I would use LINQ for this:
first9char = first9char.Where(x => x != clickValue).ToArray();
It just means "pick the items that don't match". If you can't use LINQ for some reason, then just keep another counter, and make sure to only loop to n from there on in:
int n = 0;
for(int i = 0; i < first9char.Length; i++) {
if(first9char[i] != clickValue) {
first9char[n] = first9char[i];
n++;
}
}
Clean and efficient.

Categories

Resources