Do not count the white space in the text box - c#

I have written a program that calculates the number of characters in a word entered in the text box, but I do not want to count the number of whitespaces.
What code should I write? For example, when Max is written inside the text box, the number of letters is 3 and 3 appears in other textbox, then if whitespace is used in textbox, the number of letters remains the same as 3 and does not change.
private void textBox1_TextChanged(object sender, EventArgs e)
{
string a;
int asc , j=0;
kabir = 0;
vasit = 0;
textBox2.Text =" ";
for (int i = 0; i < textBox1.Text.Length; i++)
{
int t = abjad_kabir(Char.ConvertToUtf32(textBox1.Text.Substring(i, 1), 0));
textBox2.Text = Convert.ToString(t);
j++;
// I want to do not appear number of white spaces in textbox3 and just count number of letters
textBox3.Text = Convert.ToString(j);
}
}

Remove all the characters that you don't want with a regular expression and count the remaining characters:
var text = "Max Length";
Console.WriteLine("Length={0}", Regex.Replace(text, #"\W+", "").Length);

You could also use Linq for this:
var count = text.Count(c => c != ' ');

I could delete white spaces by Trim() method.
private void textBox1_TextChanged(object sender, EventArgs e)
{
string a;
int asc, j = 0;
kabir = 0;
vasit = 0;
textBox2.Text = " ";
string s, m;
for (int i = 0; i < textBox1.Text.Length; i++)
{
int p = Char.ConvertToUtf32(textBox1.Text.Substring(i, 1), 0);
int t = abjad_kabir(p);
textBox2.Text = Convert.ToString(t);
s = textBox1.Text;
m = s.Trim();
textBox3.Text = Convert.ToString(m.Length);
}
}

Related

Is it possible to write into a RichTextBox at a given line, column?

I have a WinForm with a RichTextBox.
I am trying to write into the RichTextBox at a given line and column:
Here is the code:
public Form1()
{
InitializeComponent();
richTextBox1 = new RichTextBoxWithMouseSelectionFixed();
richTextBox1.Location = new System.Drawing.Point(62, 46);
richTextBox1.Name = "richTextBox1";
richTextBox1.Size = new System.Drawing.Size(461, 391);
richTextBox1.TabIndex = 0;
richTextBox1.Text = "";
richTextBox1.HideSelection = false;
Controls.Add(richTextBox1);
int line = 3;
int column = 5;
GoToLineAndColumn(richTextBox1, line, column);
}
private RichTextBoxWithMouseSelectionFixed richTextBox1;
private void GoToLineAndColumn(RichTextBox richTextBox1, int line, int column)
{
int offset = 0;
for (int i = 0; i < line - 1 && i < richTextBox1.Lines.Length; i++)
{
offset += richTextBox1.Lines[i].Length + 1;
}
richTextBox1.Focus();
richTextBox1.Select(offset + column, 0);
}
I tryed to write with:
richTextBox1.AppendText("currentWord");
and also with:
richTextBox1.Text = "currentWord";
but in both cases the currentWord is written in the first line at column 0.
public Form1()
{
InitializeComponent();
int line = 6;
int column = 30;
RichTextBox richTextBox1 = new RichTextBox();
richTextBox1.Location = new System.Drawing.Point(62, 46);
richTextBox1.Name = "richTextBox1";
richTextBox1.Size = new System.Drawing.Size(461, 391);
richTextBox1.TabIndex = 0;
richTextBox1.Text = "";
richTextBox1.HideSelection = false;
Controls.Add(richTextBox1);
for (int i = 0; i < line - 1; i++)
richTextBox1.Text += "\n";
for (int i = 0; i < column - 1; i++)
richTextBox1.Text += " ";
richTextBox1.Text += "Just Text";
}
The RichTextBox class has properties you can use to write text to a specific index in it. first you define the zero based index of the line and column you would like to write to and then you get the index of the first character in that line like below
// define the index of the line and the column of the line you want to write to in the rich text box
int lineIndex = 2;
// zero-based index of the line
int columnIndex = 10;
// Get the index of the first character in that line you specified above
int index = richTextBox.GetFirstCharIndexFromLine(lineIndex) + columnIndex;
//declare the string you wish to paste
string mytext = "Write to this section only";
//Use the SelectionStart and SelectionLength properties to write the text
richTextBox.SelectionStart = index;
richTextBox.SelectionLength = mytext.Length;
// clear any previous selection
richTextBox.SelectedText = mytext;
The only solution I found is by adding empty lines before the text and blank characters before the text:
private void WriteAtLineAndColumn(RichTextBox richTextBox1, string text, int line, int column)
{
// Insert blank lines at the beginning of the RichTextBox.
for (int i = 0; i < line - 1; i++)
{
richTextBox1.AppendText(Environment.NewLine);
}
int index = richTextBox1.GetFirstCharIndexFromLine(line - 1);
richTextBox1.Select(index, 0);
string spaces = new string(' ', column);
richTextBox1.SelectedText = spaces + "This is a sample text";
// Insert the text at the desired position.
richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(line - 1) + column, 0);
richTextBox1.SelectedText = text;
}

Limit line length in multiline textbox

I need to limit the number of characters on a single line that a user can enter into a multiline textbox. I have a function that can do that for data typed in, but not for data cut and pasted in.
I've tried reading the textbox into an array, using substring, and copying back to the text string, but this code (posted) throws an exception.
private void LongLine_TextChanged(object sender, TextChangedEventArgs e)
{
int lineCount =
((System.Windows.Controls.TextBox)sender).LineCount;
//string newText = "";
for (int i = 0; i < lineCount; i++)
{
if
(((System.Windows.Controls.TextBox)sender).GetLineLength(i) > 20)
{
string textString = ((System.Windows.Controls.TextBox)sender).Text;
string[] textArray = Regex.Split(textString, "\r\n");
textString = "";
for (int k =0; k < textArray.Length; k++)
{
String textSubstring = textArray[k].Substring(0, 20);
textString += textSubstring;
}
((System.Windows.Controls.TextBox)sender).Text = textString;
}
}
e.Handled = true;
}
This does what you seem to be asking for:
It truncates the end of any line that is longer than 20 as you type and when you paste or otherwise change the text.
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
const int MAX_LINE_LENGTH = 20;
var textbox = sender as TextBox;
var exceedsLength = false;
// First test if we need to modify the text
for (int i = 0; i < textbox.LineCount; i++)
{
if (textbox.GetLineLength(i) > MAX_LINE_LENGTH)
{
exceedsLength = true;
break;
}
}
if (exceedsLength)
{
// Split the text into lines
string[] oldTextArray = textbox.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var newTextLines = new List<string>(textbox.LineCount);
for (int k = 0; k < oldTextArray.Length; k++)
{
// truncate each line
newTextLines.Add(string.Concat(oldTextArray[k].Take(MAX_LINE_LENGTH)));
}
// Save the cursor position
var cursorPos = textbox.SelectionStart;
// To avoid the text change calling back into this event, detach the event while setting the Text property
textbox.TextChanged -= TextBox_TextChanged;
// Set the new text
textbox.Text = string.Join(Environment.NewLine, newTextLines);
textbox.TextChanged += TextBox_TextChanged;
// Restore the cursor position
textbox.SelectionStart = cursorPos;
// if at the end of the line, the position will advance automatically to the next line, supress that
if (textbox.SelectionStart != cursorPos)
{
textbox.SelectionStart = cursorPos - 1;
}
}
e.Handled = true;
}

Counting the number of highlighted words in richtextbox using c#

private void button2_Click(object sender, EventArgs e)
{
string[] show = richTextBox1.Text.Split(' ');
string type = textBox1.Text;
for (int i = 0; i < show.Length; i++)
{
int num = 0;
if (show[i] == textBox1.Text)
num++;
}
Label1.Text = num.ToString();
}
Im using richTextBox1 to display the file and the textBox1 to search for a word and highlight it. I want to display how many words are highlighted in the label box but it always shows zero. Any help is appreciated.
You should move int num = 0; out of your loop, since in each iteration it will be set to 0;
You need to consider the new line character condition.
In my example, I remove Chr(13) and replace Chr(10) with a space, so it behaves the same way as a space character:
string[] show = richTextBox1.Text.Replace(Convert.ToChar(13).ToString(), " ").Replace(Convert.ToChar(10).ToString(), " ").Split(' ');
string type = textBox1.Text;
int num = 0;
for (int i = 0; i < show.Length; i++)
{
if (show[i].Trim() == textBox1.Text)
num++;
}
textBox1.Text = num.ToString();

How to display the result of a char variable in a Windows Form Based application using C#

public void caesarcipher()
{
char c, a;
string PT = textBox1.Text;
PT = PT.ToLower();
for (int i = 0; i < PT.Length; i++)
{
c = Convert.ToChar(PT.Substring(i, 1));
if ((int)c + 3 > 122) a = (char)(c + 3 - 26);
else a = (char)(c + 3);
label2.Text = a; //error here as label can not display char
}
}
private void button1_Click(object sender, EventArgs e)
{
caesarcipher();
}
That is my partial code, what I want is that to display all the elements stored in char a in a label and converting the char a to string displays only the last element which does not help.
I hope I am clear enough.
This did the trick thanks to #BradleyUffner and #ChrisDunaway
public void caesarcipher()
{
char c, a;
string PT = textBox1.Text;
PT = PT.ToLower();
label2.Text = " "; //added this line
for (int i = 0; i < PT.Length; i++)
{
c = PT[i]; //changed
//c = Convert.ToChar(PT.Substring(i, 1));
if ((int)c + 3 > 122) a = (char)(c + 3 - 26);
else a = (char)(c + 3);
label2.Text += a.ToString(); //changes here solved the error
}
}
You just need to add each character to the label2.Text property instead of reassigning the property. You can also get rid of some of the explicit casting; char will get cast to an int implicitly when added to an `int:
public void CaesarCipher()
{
label2.Text = "";
foreach (var character in textBox1.Text.ToLower())
{
var intVal = character + 3;
label2.Text += (char)(intVal > 122 ? intVal - 26 : intVal);
}
}
Unless I'm missing something, a will ever only hold a single char since you defined it as char a and are setting it equal to a char.
For this, you would need to change the definitions to char[] a = new char[PT.Length]
Instead calling a =, you would then have to use the index to set the char at the location to what you want. Replacing a = with a[i] = would suffice.
To display the char array, label2.Text = new string(a) will do the trick.
public void caesarcipher()
{
string PT = textBox1.Text;
PT = PT.ToLower();
char c;
char[] a = new char[PT.Length];
for (int i = 0; i < PT.Length; i++)
{
c = Convert.ToChar(PT.Substring(i, 1));
if ((int)c + 3 > 122) a[i] = (char)(c + 3 - 26);
else a[i] = (char)(c + 3);
}
label2.Text = new string(a);
}
private void button1_Click(object sender, EventArgs e)
{
caesarcipher();
}

How to randomly generate 1000 sequences of 6 digit number

I want to generate 1000 number randomly and put the result in a rich text box ,but the result I got from my code is just one number appearing in the rich text box !!
private Random _random = new Random();
int min = 000000;
int max = 999999;
string s;
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000; i++)
{
s = _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
}
You are overriding the value of s each time you get your next number. Instead you have to add the number to a list. Something like this would work.
List<string> numbers = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000; i++)
{
numbers.Add(_random.Next(min, max).ToString("D6"));
}
richTextBox1.Text = string.Join(Environment.NewLine, numbers);
}
As most of the answers here using the .net class Random i would not use it, because in a direct comparison it doesn't creates strong random numbers.
Example:
So if you want strong random numbers you should refrain from using Random and use the RNGCryptoServiceProvider from the namesapace System.Security.Cryptography
ExampleCode:
private RNGCryptoServiceProvider _random = new RNGCryptoServiceProvider ();
int min = 000000;
int max = 999999;
private void Form1_Load(object sender, EventArgs e)
{
int[] results = new int[1000];
var buffer = new byte[4];
int min = 100000;
int max = 999999;
for (int i = 0; i < results.Length; i++) {
while(results[i] < min || results[i] > max)
{
_random.GetBytes(buffer);
results[i] = BitConverter.ToInt32(buffer, 0);
}
richTextBox1.Text += results[i].toString();
}
}
You actually need to concatenate the result with previous calculated result, right now it is replacing the string value in s every time loop executes and you end up only with the last value in s, a quick fix is to use contatination using +:
for (int i = 0; i < 1000; i++)
{
s+= _random.Next(min, max).ToString("D6") + "\n"; // now it keeps previous values as well
}
Problem is that you actually overwrite at each iteration the string s. You need to append the number to the old ones.
for (int i = 0; i < 1000; i++)
{
s += _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
You could also use AppendText method
for (int i = 0; i < 1000; i++)
{
richTextBox1.AppendText(_random.Next(min, max).ToString("D6") + "\n");
}
Suggestion by Matthew Watson: When generating such a large string it is very adviseable to use a StringBuilder. Is has much better performance than a normal concatenation of strings:
StringBuilder sb = new StringBuilder(8000);
for (int i = 0; i < 1000; i++)
{
sb.AppendLine(_random.Next(min, max).ToString("D6"));
}
richTextBox1.Text = sb.ToString();
s += _random.Next(min, max).ToString("D6") + "\n";
^
|
---- You're missing this plus sign
on this line of code you override the Text of richTextBox1
for (int i = 0; i < 1000; i++)
{
s = _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
just change it to (add a + after s)
for (int i = 0; i < 1000; i++)
{
s += _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
Note that the maxValue or Random.Next is exclusive, so 999999 is never genereted.
var numbers = Enumerable.Repeat(new Random(), 1000)
.Select(r => r.Next(1000000).ToString("D6")); // the same new Random() instance is used for all .Next
richTextBox1.Text = string.Join("\r\n", numbers);
Or a bit more efficient:
richTextBox1.Text = Enumerable.Repeat(new Random(), 1000).Aggregate(new StringBuilder(7000)
, (b, r) => b.AppendFormat("{0:D6}\n", r.Next(1000000))).ToString(0, 6999);
just You need to add ' + ' for the richtextbox1 as like below
try this one
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000; i++)
{
s = _random.Next(min, max).ToString("D6") + "\n";
richTextBox1.Text + = s;
}
}

Categories