Next textbox line - c#

I have a multi-line textbox of sequences, which the game will play one after the other. For example, the textbox may contain this:
RGBY
YGBR
RGBB
I understand that to read the first line of a multi-line textbox, I must write this:
First sequence:
textBox1.Lines[0].Length //Reads first line only for sequence 1
But how can I make it read the next line in a general sense? n+1 where n is the previous line.
New sequence:
textBox1.Lines[0 + 1].Length //Go to next line for future sequences
Any help is appreciated. Thank you in advance!

You need to store the current index in a variable, a field or property in your class.
private int CurrentIndex { get; set; }
Now you can iterate all lines, for example in a button-click event handler where you want to advance to the next line until end:
if (CurrentIndex + 1 < textBox1.Lines.Length)
{
string currentLine = textBox1.Lines[++CurrentIndex];
}

for(int i=0; i < textBox1.Lines.Count(); i++)
{
var currentLine = textBox1.Lines[i];
// do what you want with current line
}

Related

How can I check for integers in list and print the index of them?

so my problem is that I don't know how to go forward in the list and print the next same integer if there is one.
Here is what I have at the moment:
while (list.Contains(input1))
{
Console.WriteLine(input1 + " is at index " + list.IndexOf(input1))
}
I am trying to list all of the integers that are in the list and print the index of them. But not remove after finding one of the integers (this was at least my first idea.).
IndexOf has an overload with two parameters, which allows you to start searching at a later position in the list.
Since this is obviously a learning exercise, I won't spoil it by providing the full code, but rather suggest that you try to implement the following algorithm:
Find the index of input starting at position 0.
If not found (i.e., IndexOf returns -1): we're done. Otherwise:
Print and remember that index.
Start again at step 1, but this time, don't start searching at 0 but at the index you remembered + 1.
You can do the following:
go through the list/array using for statement
for(int i=0; i < list.length; i++) // loop though list
then inside the loop check the value of the current item using if statement:
if(list[i] == input1)
//do smothing
The list[0] represent the first item in the array, which means the index is 0.
so in the example above the i will be the current index so long that you in the loop.
I didn't write the full code for learning purpose in reference to #Heinzi answer.
Hope that could be helpful!
This is an implementation possibility. It is longer than it has to be, but it makes it clearer for beginners how one could tackle this problem.
Since you wanted to only show numbers that come up more than once here is an implementation method. If you want to show numbers that come up only once too just erase everything about lastindex
List<int> yourlist = new List<int> { 1,1,1,1,1,11,2,3,3,4,4,5 };
int input = 0;
input = Convert.ToInt32(Console.ReadLine());
var index = yourlist.IndexOf(input);
//this checks if your input is in the list
var lastindex = yourlist.LastIndexOf(input);
//this does the same but it searches for the last implementation of your input
if (index != -1 && lastindex != index)
//this if checks if your number comes up more than once. IndexOf returns -1 if there is no occurence of your input
{
Console.Write($"the index of {input} is {index}");
for (int i = index+1; i <= yourlist.Count; i++)
//this loop takes the position of the first occurence of your number and then counts up from there
{
var tempindex = yourlist.IndexOf(input, i);
if (tempindex != -1)
//this if lets everything except -1 through
{
Console.Write($" and {tempindex}");
}
}
}
else
{
Console.WriteLine("your number cannot be found twice in the list");
}

Delete some part of selected listbox item

I want to delete some parts (string or int values) for selected listbox item in C#.
As shown on picture I get some random coordinates on picturebox which is shown on Listbox1. Then I selected randomly these points to add Listbox2 by ADD button. I want make new arrangement at Listbox2 which means it should be 1.selected point 2.3.4.selected points ..(not randomly 3.rd 6.th 7.th ..)
Secondly I want to transfer to coordinate (just numbers) to Listbox3. How can I do?
(source: hizliresim.com)
To add selected coordinate
private void add()
{
int c = listBox1.Items.Count - 1;
for (int i = c; i >= 0; i--)
{
if (listBox1.GetSelected(i))
{
int a = listBox2.Items.Count + 1;
listBox2.Items.Add(a+" "+listBox1.Items[i]);
// listBox1.Items.RemoveAt(i);
}
}
}
The question is not really clear but i will try to give you an answer as good as i understood the question. So from what i got you would like to make it so the numbers are "1 ,2 ,3 ..." in ListBox2 instead of random once and also you would like the same result but only the numbers in ListBox3.
Hope this help at least this is what i understood you are trying to do. Btw all this is assuming that all your data is based on the example you provided!
//We are going to read the string from the first box and find the first
//occurence of "." and get the rest of the string after that we are going to add it to ListBox2
string for_lisbox2 = listBox1.Items[i].ToString();
for_lisbox2 = for_lisbox2.Substring(for_lisbox2.IndexOf('.'));
int current_index = listBox2.Items.Count + 1;
listBox2.Items.Add(current_index + for_lisbox2);
//Then we do something similar but this time we are finding last empty space " " so we can find the start of the second coordinates and we mark it as Y
//then we do the same with X and finaly we add them to Lisbox3
string for_listbox3 = for_lisbox2;
//finding second set of coordinates by finding the last occurence of ' ' and using the result for a start index of Substring method this will return the second number
string Y = for_listbox3.Substring(for_listbox3.LastIndexOf(' '));
// this is just to remove the numbers that we just got in the previous line so they are not in your way for the next operation
for_listbox3 = for_listbox3.Substring(0, for_listbox3.LastIndexOf(' '));
//this is just like geting the other number
string X = for_listbox3.Substring(for_listbox3.LastIndexOf(' '));
for_listbox3 = X + " " + Y;//displaying the results in ListBox3 as "72 134"
listBox3.Items.Add(for_listbox3);
.

Get line with starts with some number

I have a file and I have to process this file, but I have to pick just the last line of the file, and check if this line begins with the number 9, how can I do this using linq ... ?
This record, which begins with the number 9, can sometimes, not be the last line of the file, because the last line can be a \r\n
I maded one simple system to make thsi:
var lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].StartsWith("9"))
{
//...
}
}
But, I whant to know if is possible to make something more fast... or, more better, using linq... :)
string output=File.ReadAllLines(path)
.Last(x=>!Regex.IsMatch(x,#"^[\r\n]*$"));
if(output.StartsWith("9"))//found
The other answers are fine, but the following is more intuitive to me (I love self-documenting code):
Edit: misinterpreted your question, updating my example code to be more appropriate
var nonEmptyLines =
from line in File.ReadAllLines(path)
where !String.IsNullOrEmpty(line.Trim())
select line;
if (nonEmptyLines.Any())
{
var lastLine = nonEmptyLines.Last();
if (lastLine.StartsWith("9")) // or char.IsDigit(lastLine.First()) for 'any number'
{
// Your logic here
}
}
You don't need LINQ something like following should work:
var fileLines = File.ReadAllLines("yourpath");
if(char.IsDigit(fileLines[fileLines.Count() - 1][0])
{
//last line starts with a digit.
}
Or for checking against specific digit 9 you can do:
if(fileLines.Last().StartsWith("9"))
if(list.Last(x =>!string.IsNullOrWhiteSpace(x)).StartsWith("9"))
{
}
Since you need to check the last two lines (in case the last line is a newline), you can do this. You can change lines to however many last lines you want to check.
int lines = 2;
if(File.ReadLines(file).Reverse().Take(lines).Any(x => x.StartsWith("9")))
{
//one of the last X lines starts with 9
}
else
{
//none of the last X lines start with 9
}

problem with binarysearch algorithm

the code below belongs to binary search algorithm,user enter numbers in textbox1 and enter the number that he want to fing with binarysearch in textbox2.i have a problem with it,that is when i enter for example 15,21 in textbox1 and enter 15 in textbox2 and put brakpoint on the line i commented below,and i understood that it doesnt put the number in textbox2 in searchnums(commented),for more explanation i comment in code.thanks in advance
public void button1_Click(object sender, EventArgs e)
{
int searchnums = Convert.ToInt32(textBox2.Text);//the problem is here,the value in textbox2 doesnt exist in searchnums and it has value 0.
int result = binarysearch(searchnums);
MessageBox.Show(result.ToString());
}
public int binarysearch(int searchnum)
{
string[] source = textBox1.Text.Split(',');
int[] nums = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
int first =0;
int last = nums.Length-1;
while (1<= nums.Length)
{
int mid = (int)Math.Floor(first+last / 2.0);
if (first > last)
{
break;
}
if (searchnum < nums[mid])
{
last = mid - 1;
}
if (searchnum > nums[mid])
{
first = mid + 1;
}
else
{
return nums[mid];
}
}
return -1;
}
First, when you know you can place a breakpoint on a line, you sure know you can step through the whole program and see what values are in each variable or property. So, go ahead, and debug. Among other things you are probably missing data input validation in your program.
Second, your binary search implementation is missing mid recalculation after first or last is updated and a stop condition in case the number being looked for is not found in the array. You have to break the loop in case first == last, regardless if nums[mid] matches or not — nobody said the number from textbox2 must be in the array.
What does it have to do with binary search? The problem seems to be that you can't read the number out of a textbox. Are you sure it's the right textbox? What is it's Text? Also, if you put the breakpoint ON the line that assigns the value to searchnums, it will be 0, because it hasn't been assigned yet, put the breakpoint on the line AFTER.
OK, first of all, I hope you know that binary search won't work if nums isn't sorted.
That said, there are a few problems in the algorithm. First of all, you're not changing any of the key elements in the loop. You're only changing first and last in the loop and they aren't even used there, so the loop's state doesn't change.
So i guess you meant to have this line in the beginning of the loop:
mid = (first +last)/2;
Besides that, you need to check for the very likely event that the number doesn't exist. which means adding this in the beginning of the loop to:
if (last < first) break;
Which of course means that the first point of the array block has passed the last point, which means the block size is negative. first == last may be legal when you get to the last cell in the array.
And the last point is to initiate last as size-1:
int last = nums.Length - 1;
We're talking about array indexes after all.

Retrieving an accurate string array from a RichTextBox control

I have a RichTextBox control on my form. The control is setup in such a way that it will wrap to the next line after 32 lines of text are input. The problem I'm having is I want to be able to retreive an array of strings representing the lines in my control. I know there is a Lines property attached to the RichTextBox, but I am experiencing 2 issues with it:
1) I ONLY want an array of strings showing the lines that are visible on the screen only. Right now the Lines array returns every single line in the RichTextBox. I only want the lines visible on the screen returned.
2) The Lines property is not giving me a true representation of my lines. It counts a "line" as a line of text ended by a carriage return or \n. So in other words, if I type 64 characters and none of them are a carriage return, then it should return 2 lines (because there are 32 characters per line). Instead, it doesn't return any lines until I hit enter. Even then, it only returns 1 line, not 2. Its acting more like a Paragraph property, if there was such a thing.
Anyone know a way around these 2 issues?I am using C# btw
You have to do a few tricks to achieve this which have to do with querying for the position of the actual lines according to the character index. The following program shows one way of doing this. You might have to harden it a bit, but it should get you started:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
if (richTextBox1.Text == "")
return;
// Lines corresponding to the first and last characters:
int firstLine = richTextBox1.GetLineFromCharIndex(0);
int lastLine = richTextBox1.GetLineFromCharIndex(richTextBox1.Text.Length);
// Get array of lines:
List<string> lines = new List<string>();
for (int i = firstLine; i <= lastLine; i++)
{
int firstIndexFromLine = richTextBox1.GetFirstCharIndexFromLine(i);
int firstIndexFromNextLine = richTextBox1.GetFirstCharIndexFromLine(i + 1);
if (firstIndexFromNextLine == -1)
{
// Get character index of last character in this line:
Point pt = new Point(richTextBox1.ClientRectangle.Width, richTextBox1.GetPositionFromCharIndex(firstIndexFromLine).Y);
firstIndexFromNextLine = richTextBox1.GetCharIndexFromPosition(pt);
firstIndexFromNextLine += 1;
}
lines.Add(richTextBox1.Text.Substring(firstIndexFromLine, firstIndexFromNextLine - firstIndexFromLine));
}
// Print to richTextBox2 while debugging:
richTextBox2.Text = "";
foreach (string line in lines)
{
richTextBox2.AppendText(">> " + line + Environment.NewLine);
}
}
}

Categories