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));
}
Related
Trying to remove a Dot from a String i´m experiencing a problem. With different Chars such as "," or "-" its working properly but the Dot won´t disappear.
Got a TextBox with the Name nr_tb. I Input Hello.World and my MessageBox outputs the same. Changing the Dot in the Replace function with a "," works.
Not working:
string line;
private void nr_tb_TextChanged(object sender, TextChangedEventArgs e)
{
line = nr_tb.Text.Replace(".","");
MessageBox.Show(line);
}
Working:
string line;
private void nr_tb_TextChanged(object sender, TextChangedEventArgs e)
{
line = nr_tb.Text.Replace(",","");
MessageBox.Show(line);
}
string number= "2.36";
string newNumber = number.Replace(".", "");
It might be another character that seems like a DOT. Char code of DOT is 46 so if you get this char code in your string you can easily Replace(".", ""); it.
This method show each char code of a string:
private static string DotRemover(string temp)
{
string _Result = string.Empty;
foreach (byte a in Encoding.UTF8.GetBytes(temp.ToCharArray()))
{
_Result += a.ToString() + Environment.NewLine;
}
return _Result;
}
OR
you can replace everything that look likes a DOT :
public static string CleanNumb(string numb)
{
foreach (char c in ".,'´")
numb = numb.Replace(c, ' ');
return numb.Replace(" ", "");
}
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'
}
}
I split text from a text file and I have to compare 2 strings, one from a textbox and the other one from a text file from a specific line. That string from text has a space at the end and the comparison is always wrong.
Here is the code. Thank you!
private void button1_Click(object sender, EventArgs e)
{
Random r = new Random();
t = r.Next(1,30);
StreamReader sr = new StreamReader("NomenA1.txt");
cuv = sr.ReadToEnd().Split('\n');
string original = cuv[t];
Random num = new Random();
// Create new string from the reordered char array.
string rand = new string(original.ToCharArray().
OrderBy(s => (num.Next(2) % 2) == 0).ToArray());
textBox2.Text = rand;
button1.Visible = false;
button2.Visible = true;
}
private void button2_Click(object sender, EventArgs e)
{
button1.Visible = false;
string a =Convert.ToString(textBox1.Text.ToString());
string b = cuv[t];
if (a == b)
{
MessageBox.Show("Corect");
button1.Visible = true;
button2.Visible = false;
}
else
{
MessageBox.Show("Mai incearca"); button1.Visible = false;
}
}
You can use Regex to remove all last space:
string s = "name ";
string a = Regex.Replace(s, #"\s+$", "");
or Trim() function for all both end space:
string s = " name ";
string a = s.Trim();
or if you want to remove only one space from the end:
string s = "name ";
string a = Regex.Replace(s, #"\s$", "");
How could I remove the last character in a string
var s = "Some string ";
var s2 = s.Substring(0, s.Length - 1);
Alternatively a general solution is usually
var s3 = s.Trim(); // Remove all whitespace at the start or end
var s4 = s.TrimEnd(); // Remove all whitespace at the end
var s5 = s.TrimEnd(' '); // Remove all spaces from the end
Or a very specific solution
// Remove the last character if it is a space
var s6 = s[s.Length - 1] == ' ' ? s.Substring(0, s.Length - 1) : s;
Have you tried .Trim()
String myStringA="abcde ";
String myStringB="abcde";
if (myStringA.Trim()==myStringB)
{
Console.WriteLine("Matches");
}
else
{
Console.WriteLine("Does not match");
}
What about :
string s = "name ";
string a = s.Replace(" ", "");
That seems pretty simple to me, right?
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);
}
I want to auto format a text entered in a textbox like so:
If a user enters 2 characters, like 38, it automatically adds a space. so, if I type 384052
The end result will be: 38 30 52.
I tried doing that, but it's ofr some reason right to left and it's all screwed up.. what I'm doing wrong?
static int Count = 0;
private void packetTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
Count++;
if (Count % 2 == 0)
{
packetTextBox.Text += " ";
}
}
Thanks!
It's much nicer if you just let the user type and then modify the contents when the user leaves the TextBox.
You can do that by reacting not to the KeyPress event, but to the TextChanged event.
private void packetTextBox_TextChanged(object sender, EventArgs e)
{
string oldValue = (sender as TextBox).Text.Trim();
string newValue = "";
// IF there are more than 2 characters in oldValue:
// Move 2 chars from oldValue to newValue, and add a space to newValue
// Remove the first 2 chars from oldValue
// ELSE
// Just append oldValue to newValue
// Make oldValue empty
// REPEAT as long as oldValue is not empty
(sender as TextBox).Text = newValue;
}
On TextChanged event:
int space = 0;
string finalString ="";
for (i = 0; i < txtbox.lenght; i++)
{
finalString = finalString + string[i];
space++;
if (space = 3 )
{
finalString = finalString + " ";
space = 0;
}
}
I used
int amount;
private void textBox1_TextChanged(object sender, EventArgs e)
{
amount++;
if (amount == 2)
{
textBox1.Text += " ";
textBox1.Select(textBox1.Text.Length, 0);
amount = 0;
}
}
Try this..
on TextChanged event
textBoxX3.Text = Convert.ToInt64(textBoxX3.Text.Replace(",", "")).ToString("N0");
textBoxX3.SelectionStart = textBoxX3.Text.Length + 1;