I'm trying to make a Reddit Formatter tool for whenever you have a text with just one line break to add another and make a new paragraph. Here in StackOverflow it's the same, you have to press the enter key twice to start a new paragraph. It'd go from:
Roses are red
Violets are Blue
to
Roses are red
Violets are Blue
It's actually pretty easy, and I've managed to do this code below by myself (probably messy, but it works!!) which for the moment replaces the 'a' characters from the textBox to 'e' after pressing a button.
private void button1_Click(object sender, EventArgs e)
{
Char[] textBox1Array = textBox1.Text.ToCharArray();
for (int i = 0; i < textBox1Array.Length; i++)
{
if (textBox1Array[i] == 'a')
{
textBox1Array[i] = 'e';
}
}
textBox1.Text = String.Concat(textBox1Array);
}
The real question is: how do I use the enter key instead of 'a'? HTML code obviously doesn't seem to work:
(
)
and with
\r\n
it throws another error because it doesn't consider it a single character (too many characters in character literal)
A linebreak is not necessarily the same on all systems. So if a user entered his text on Windows the linebreak could lok other than if the text was entered under Linux. So Environment.Newline won't work here. You need to check for several line break types. I would recommend to do the following:
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Replace("\r\n", "\r")
.Replace("\n\r", "\r")
.Replace("\n", "\r")
.Replace("\r", "\r\n\r\n");
}
This way you will replace all (at least the ones I know) possible line break types with a placeholder and then replace that placeholder with a double linebreak (In this case the Windows version).
The straight forward answer would be:
textBox1Array[i] = '\n';
another possibility would be to use the decimal code of new line:
textBox1Array[i] = Convert.ToChar(10);
it will automatically feed back the cursor
You could actually use the string directly without any conversion into an unflexible array. Use a reverse for-loop and access the chars with the [ ] operator, (because string is internally represented as a char-array):
string g = "Roses are red \r\nViolets are Blue";
for (int i = g.Length -1; i >= 0; i--)
{
if (g[i] == '\n')
{
g = g.Insert(i, Environment.NewLine);
// or as a string you can use your former logic
g = g.Insert(i, "\r\n");
}
}
For me it seems the question is about what character stands for enter key, so I'll try answer that.
In my case it was '\r'. To make sure, try this code:
// you need to add textBox1 to try it or just use what's inside the method
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == '\r')
MessageBox.Show("Test");
}
Set a breakpoint on the if line, run the program and press Enter, when it stops on breakline add watch on e and look into its fields. You'll see what character is under e.KeyChar.
What I understand, is that you want where ever your program
intercepts a single newline character it should start a new
paragraph (i.e. "end of a line then a new line + new line).
I suggest two ways to achieve this,
1> On click of a button
2> when user hits the 'Enter/Return' key on keyboard
it should add a new paragraph just like in "MSWord"
For this test, I have put 2 textboxes, TextBox1 , TextBox2,
one command button (btnFormat) that would only work on TextBox1.
following is the code:
private void btnFormat_Click(object sender, EventArgs e)
{
if(String.IsNullOrWhiteSpace(textBox1.Text) == true) return;
//searches for the new line character
Int32 i = textBox1.Text.IndexOf("\r\n");
Int32 j = 0;
if (i == -1) return; //new line character not found
String strA = "";
String strB = "";
//now pass the value in 'i' to 'j'
Int32 icnt = 0;
while(true)
{
//j : from where search should begin. Therefore, it is set
//to a position ahead of last occurence of new line charachter(\r\n)
//i.e. value in 'i'
//i : current occurence of new line character
//scan for the next occurence of new line character from
//current positon
i = textBox1.Text.IndexOf("\r\n",j);
if (i == -1) break;
//there is a possibility of some space(s) or no character at all
//between the last position and current position, then in such a
//case we will remove that newly found new line characters so that
//the formatting is uniform
//all text before new line
strA = textBox1.Text.Substring(0, i);
//all textbox after the new line
strB = textBox1.Text.Substring(i + 2);
if (String.IsNullOrWhiteSpace(textBox1.Text.Substring(j, i - j)) ==
false)
{
textBox1.Text = strA + "\r\n\r\n" + strB;
j = i + 4;
}
else
{
textBox1.Text = strA + strB;
//do not change the value of 'j'
}
}
//increment i and now again scan from this position
//for another new line character
}
Case2:[when entering text or in a previously entered texts]
when user hits the 'Enter/Return' key on keyboard,
like in MSWord, the program automatically start a new paragraph (i.e.
Add two new line characters (\r\n\r\n).
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
e.KeyChar = '\0';//this will suppress current {Return key}
Int32 i = textBox2.SelectionStart;//your current cursor position
String sa = textBox2.Text.Substring(0,i);//text before this pos.
String sb = textBox2.Text.Substring(i);//text beyond from this pos
textBox2.Text = sa + ("\r\n\r\n") + sb;
textBox2.SelectionStart = i + 2;
//if there is already one or more new line characters, then
//this code does not check for that, so it has to be removed
//manually using 'delete' or 'backspace'
}
}
Related
My Professor gave us this question
Write a method called Drawline that accepts as input an integer n and generates a line of output in lstOutput with n hyphens. That is, if n = 5 we have a line of ‘-----‘ displayed in the list box.
Basically he wants me to type a number in a text box and when i click the button it should display that many hyphens in a list box. Using visual Studio C# WindowsFormApp.
Here's my code:
private void btn3_Click(object sender, EventArgs e)
{
double n;
Drawline(out n);
}
private void Drawline(out double n)
{
n = double.Parse(textBox1.Text);
string strline = "";
for (n = 1; n <= 5; n++);
strline += '-';
lstOutput.Items.Add(String.Format(strline, n));
}
It works but no matter what number i put in the text box only one hyphen shows up. Can anyone help me?
The problem is with your for loop in DrawLine method.
You need to remove the semi-colon at the end of the for statement, so the strLine += '-'; will belong to the loop, not just be executed once.
private void Drawline(out double n)
{
n = double.Parse(textBox1.Text);
string strline = "";
for (i = 1; i <= 5; i++)
strline += '-';
lstOutput.Items.Add(String.Format(strline, n));
}
It appears you may be making this more complicated than it has to be.
It is unclear “why” the DrawLine method returns a double value using the out property? Is this a requirement? If it is not a requirement, then it is unnecessary.
Also, as per the requirement… ”Write a method called Drawline that accepts as input an integer n” … if this is the requirement, I have to ask why is the method accepting a double value? This would not fit with the requirement.
Below is a simplified version and should fit your requirements. First in the button click event, we want to get the integer value from the text box. We need to assume the user typed in a value that is NOT a valid integer. If the value is NOT a valid integer greater than zero (0), then we will display a message box indicating such.
private void button1_Click(object sender, EventArgs e) {
if ((int.TryParse(textBox1.Text, out int value)) && value > 0) {
Drawline(value);
}
else {
MessageBox.Show("String is not a number or is less than 1 : " + textBox1.Text);
}
}
Next the DrawLine method that simply adds a string of “-“ character(s) to the list box. Note the passed-in/accepted value of n has already been verified as a valid integer number greater than 0.
private void Drawline(int n) {
lstOutput.Items.Add(new string('-', n));
}
If you MUST use a for loop to generate the string, it may look something like…
private void Drawline(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.Append("-");
}
lstOutput.Items.Add(sb.ToString());
}
I'm trying to move the first char of the string to the end every time I press the button.
My logic seems to only display the first output again and again after I press the button.
string input = "";
string manipulated = "";
int initial;
input = txtInput.Text;
if (txtInput.Text == String.Empty)
{
MessageBox.Show("Textbox is empty, please input a string.");
}
else
{
for (initial = 1; initial < input.Length; initial++)
{
manipulated += input[initial];
}
manipulated += input[0];
lblOutput.Text = manipulated.ToString();
input = manipulated;
manipulated = "";
}
E.g. if I enter "1234" in the text box and press the button, my output should be "2341", then after I hit the button again, the output should move to "3412" .. etc.
This is a simple example of Basics String operations:
private void ManipulateBtn_Click(object sender, EventArgs e)
{
string input = InputTxt.Text; // Read the text from you Textbox in Windos form
if (input == string.Empty)
{
return;
}
string temp = input[0].ToString(); // Create a temp for the first char(toString) from you input
input = input.Remove(0,1); // Remove (from you input) At Index 0 (the idex from fist char in string) 1 time)
input += temp; //add the firs item from you input at the end of string
InputTxt.Text = input; // prin the result in the Textbox back.
}
You can see the example SimpleStringOperation
You can Improve your code by another solution using Substring Method
Create a new variable called _number and set the value to 1
public partial class Form1: Form
{
private int _number = 1;
// ....
}
Then in Button event, you can replace your code with this code
private void BtnMoveText_Click(object sender, EventArgs e)
{
if (txtInput.Text == string.Empty)
{
MessageBox.Show(#"TextBox is empty, please input a string.");
return;
}
if (_number > txtInput.TextLength)
_number = 1;
lblOutput.Text = txtInput.Text.Substring(_number) + txtInput.Text.Substring(0, _number);
_number++;
#region ** Depending on Microsoft **
/*
Substring(Int32)
(Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.)
Parameters
startIndex Int32
The zero-based starting character position of a substring in this instance.
.......................
Substring(Int32, Int32)
(Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length..)
Parameters
startIndex Int32
The zero-based starting character position of a substring in this instance.
length Int32
The number of characters in the substring.
*/
#endregion
}
You're taking your OUTPUT and placing it in a Label...but continuing to take your INPUT from the TextBox which hasn't changed...thus the same result each time.
Simply change:
lblOutput.Text = manipulated.ToString();
To:
txtInput.Text = manipulated;
I have almost designed a notepad using c#. But only problem I'm facing now is in my statusstrip.
My need- I want to display character count per each line.
When user press enter key it should come to new line and now character count should start from 1.
Technically - Col=1, Ln=1; //(initially)Col=no of character per line Ln=line count
When user press enter key-
Ln=2 and goes on and Col=No of characters we have typed in that specific line
I've tried these lines of code -
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int count = Convert.ToInt32(e.KeyChar);
if (Convert.ToInt32(e.KeyChar) != 13)
{
Col = richTextBox1.Text.Length;
toolStripStatusLabel1.Text = "Col:" + Col.ToString() + "," + "Ln:" + Ln;
}
if (Convert.ToInt32(e.KeyChar) == 13)
{
//richTextBox1.Clear();
Ln = Ln + 1;
toolStripStatusLabel1.Text = "Col:" + Col.ToString() + "Ln:" + Ln;
}
}
Supposing you are using Windows Forms, you can use the following solution (but you have to subscribe to the SelectionChanged event instead of the KeyPress event of the rich text box control):
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
int currentIndex = richTextBox1.SelectionStart;
// Get the line number of the cursor.
Ln = richTextBox1.GetLineFromCharIndex(currentIndex);
// Get the index of the first char in the specific line.
int firstLineCharIndex = richTextBox1.GetFirstCharIndexFromLine(Ln);
// Get the column number of the cursor.
Col = currentIndex - firstLineCharIndex;
// The found indices are 0 based, so add +1 to get the desired number.
toolStripStatusLabel1.Text = "Col:" + (Col + 1) + " Ln:" + (Ln + 1);
}
How do I get the last entered word in RichEditControl
here my code
private void richEditControl1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == ' ')
{
int wordEndPosition = richEditControl1.Document.CaretPosition.ToInt();
int currentPosition = wordEndPosition;
while (currentPosition > 0 && richEditControl1.Text[currentPosition - 1] != ' ')
{
currentPosition--;
}
string word = richEditControl1.Text.Substring(currentPosition, wordEndPosition - currentPosition);
this.Text = "Last char typed: " + word;
}
}
But when i press Enter create new line, it was wrong.
I guess you want to get a word whether it is surrounded by spaces or new lines, as long as it is the last one? Maybe you should include New Line check in your While loop, so it doesn't check just spaces.
richEditControl1.Text[currentPosition - 1] != "\n"
or something alike. Not sure if "\n" will pass , since I didn't work with such examples for some time. It probably just didn't know what to do whit new line.
Try:
public Form1()
{
InitializeComponent();
richEditControl1.KeyUp +=richEditControl1_Key;
}
private void richEditControl1_Key(object sender, KeyEventArgs e)
{
var currentText = richEditControl1.Text.Replace("\n", "");
currentText = richEditControl1.Text.Replace("\r", " ");
String result = currentText.Trim().Split(' ').LastOrDefault().Trim();
Console.WriteLine(String.Format("{0}| {1}", DateTime.Now.ToLongTimeString(), result));
}
I am working with windows form. In my project i need to color the last word of rich text box. When someone write on the given text box of the application i need the last word that is just written on the richtextbox to be colored red or whatever.
I found a way to extract the last word from the following link
http://msdn.microsoft.com/en-us/library/system.windows.documents.textselection.select%28v=vs.95%29.aspx
But i need more handy code to extract the last word if its possible. Please help.
Well, if you really are just looking to get the last word, you could do something like this...Assuming of course, that you make a string equal to the text of your rich text box.
string str="hello, how are you doing?";
if (str.Length >0)
{
int index=str.LastIndexOf(" ") + 1;
str = str.Substring(index));
}
Then just return the string, and do what you need to do with it.
Here is the sample code
*> char[] arr = new char[50];
int i = 0;
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space) {
string str = new string(arr);
MessageBox.Show(str);
Array.Clear(arr, 0, arr.Length);
i = 0;
}
else if (e.KeyCode == Keys.Back)
{
i--;
if (i < 0)
{
i = 0;
}
arr[i] = ' ';
}
else
{
arr[i] = (char)e.KeyValue;
i++;
}
}*
This is how you will be able to extract the latest word. Now color yourself the word you like.
As I remember rich text box can render text as HTML.
Just wrap your last word in font tag and that's it.