How to remove blank lines from a C# List<string>? - c#

I am trying to create a routine in C# that sorts a list added to a Multi-Line text box. Once that is done, there is an option to remove all blank lines. Can someone tell me how I would go about doing this? here is what I have so far, but it doesn't work at all when I select the box and click sort:
private void button1_Click(object sender, EventArgs e)
{
char[] delimiterChars = { ',',' ',':','|','\n' };
List<string> sortBox1 = new List<string>(textBox2.Text.Split(delimiterChars));
if (checkBox3.Checked) //REMOVE BLANK LINES FROM LIST
{
sortBox1.RemoveAll(item => item == "\r\n");
}
textBox3.Text = string.Join("\r\n", sortBox1);
}

If you're splitting the string on '\n', sortBox1 won't contain a string containing \n. I would just use String.IsNullOrWhiteSpace, though:
sortBox1.RemoveAll(string.IsNullOrWhiteSpace);

You forgot to sort the lines:
sortBox1.Sort();
A blank line is not "\r\n", that is a line break. Blank lines are empty strings:
sortBox1.RemoveAll(item => item.Length == 0);
You can also remove the blank lines when splitting the string:
private void button1_Click(object sender, EventArgs e) {
char[] delimiterChars = { ',',' ',':','|','\n' };
StringSplitOptions options;
if (checkBox3.Checked) {
options = StringSplitOptions.RemoveEmptyEntries;
} else {
options = StringSplitOptions.None;
}
List<string> sortBox1 = new List<string>(textBox2.Text.Split(delimiterChars, options));
sortBox1.Sort();
textBox3.Text = string.Join("\r\n", sortBox1);
}

Related

Trim textbox text after 20 characters used and spaces if contains spaces

I have a WinFormApp with 2 txtboxes (LongName and ShortName) with a Button.
When txt is entered in the LongName txtbox, I want to press the button to shorten all txt inside LongName txtbox to the first 20 characters imput and to remove any spaces within' the txtbox then display the results in the ShortName txtbox. I'm having a real hard time trying to get this correct. I've tried a number of ways to try but ultimately can't seem to get it right. Here is example code:
private void btnGetSN_Click(object sender, EventArgs e)
{
Regex space = new Regex(#" ");
MatchCollection spacematch = space.Matches(txtLongName.Text);
if (txtLongName.Text.Length > 20)
{
string toTrim = txtLongName.Text;
toTrim = toTrim.Trim();
txtShortName.Text = ("'" + toTrim.ToString() + "'");
}
if (spacematch.Count > 0)
{
txtLongName.Text.Replace(" ", "");
}
}//closes method
I've been able to limit the txtbox to only 20 characters in the properties but I would like to setup a If variable to allow more customization.
Am I on the right track?
No errors in the code but when executing the button, nothing happens. Any help is appreciated.
string.Replace() doesn't update the string itself, but rather returns a new string that is modified.
private void btnGetSN_Click(object sender, EventArgs e)
{
// remove space from txtLongName
txtLongName.Text = txtLongName.Text.Replace(" ", string.Empty);
// take only the first 20characters from txtLongName
txtShortName.Text = txtLongName.Text.Substring(0, Math.Min(txtLongName.Text.Length, 20));
}
EDIT: Previous code will remove space from txtLongName. If that is not intended, use this instead :
private void btnGetSN_Click(object sender, EventArgs e)
{
// remove space from txtLongName
var name = txtLongName.Text.Replace(" ", string.Empty);
// take only the first 20characters from txtLongName
txtShortName.Text = name.Substring(0, Math.Min(name.Length, 20));
}
Looks like you need to write differently
private void button1_Click(object sender, EventArgs e)
{
var shortName = txtLongName.Text.Trim().Replace(" ", "");
var maxLength = (shortName.Length > 20) ? 20 : shortName.Length;
if(txtLongName.Text.Trim().Length > 0)
txtShortName.Text = shortName.Substring(0, maxLength);
}

Seperate a label into 2 different Textbox C#

I wanted to know how i could split this label into 2 different textboxes. Before writing here i searched google and came this far, but now both of my textboxes is showing the value 1000. The program is supposed to split the numbers between the x.
Example: Left textbox = 80 & Right textbox = 1000. What am I missing?
private void Split_btn_Click(object sender, EventArgs e)
{
string s = label1.Text;
// Split string on spaces.
// ... This will separate all the words.
string[] words = s.Split('x');
foreach (string word in words)
{
Left_txtbox.Text = word;
Right_Textbox.Text = word;
}
}
The problem is the loop. You are setting both textboxes with the same value and overwriting it with every iteration so the last values wins.
You could simply assign the values like follows:
Left_txtbox.Text = words[0];
Right_Textbox.Text = words[1];
I would add the trim() command in as well because you will end up with a space after the 80 and before the 1000.
private void button1_Click(object sender, EventArgs e)
{
string s = label1.Text;
string[] words = s.Split('x');
Left_txtbox.Text = words[0].Trim();
Right_Textbox.Text = words[1].Trim();
}
or add the split directly into the textbox assign
private void button1_Click(object sender, EventArgs e)
{
string s = label1.Text;
Left_txtbox.Text = s.Split('x')[0].Trim();
Right_Textbox.Text = s.Split('x')[1].Trim();
}
Try this instead of your foreach loop:
if (words.Length > 1)
{
Left_txtbox.Text = words[0];
Right_Textbox.Text = words[1];
}

How can i parse text from textBox and add each part of the text to a string variable?

private void textBox1_TextChanged(object sender, EventArgs e)
{
}
For example i type in the textNox: החטוף נמצא בתאריך: 25.6.2014 בשעה: 13:01
Then:
string t = בשעה: 13:01
string f = בתאריך: 25.6.2014
string g = החטוף נמצא
This is a working code i did now the result/s is just what i needed:
private void textBox1_TextChanged(object sender, EventArgs e)
{
List<string> allwords = new List<string>();
string firstPart = "";
string secondPart = "";
string thirdPart = "";
int t = 0;
textBox1.ForeColor = Color.Green;
if (textBox1.Text.Contains("בתאריך"))
{
t = textBox1.Text.IndexOf("בתאריך");
firstPart = textBox1.Text.Substring(0, t);
allwords.Add(firstPart);
}
if (textBox1.Text.Contains("שעה"))
{
int x = textBox1.Text.IndexOf("שעה");
secondPart = textBox1.Text.Substring(t, x-t);
thirdPart = textBox1.Text.Substring(x);
allwords.Add("דווח במקור " + secondPart + thirdPart);
}
}
To make more variables as you described, you can use a List. It's dynamic, so you can add or remove items from it. Each item can be accessed with proper indexes, starting from 0. I think you should create an "Add"-Button next to the TextBox, which creates a new string variable of the typed text to the list.
Make a new list:
List<string> texts = new List<string>();
Then make the button and add new Click-method for it:
public void myButton_Click(object sender, EventArgs e)
{
// Add the text to the list
texts.Add(yourTextBox.Text);
// Then clear the TextBox for next input
yourTextBox.Text = "";
}
Ten you can loop through the list, accesing all the texts that were added:
foreach (string text in texts)
{
// Do something with the text...
}

How do i check if there is spaces in textBox content?

I have this code :
private void BtnScrambleText_Click(object sender, EventArgs e)
{
textBox1.Enabled = false;
BtnScrambleText.Enabled = false;
StringBuilder sb = new StringBuilder();
var words = textBox1.Text.Split(new char[] { ' ' });
for (int i = 0; i < words.Length; i++)
{
if (string.IsNullOrEmpty(words[i]))
{
sb.Append(words[i]);
}
else
{
ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(words[i]);
scrmbltb.GetText();
sb.Append(scrmbltb.scrambledWord);
}
}
textBox2.AppendText(sb.ToString());
}
For example in textBox1 i did typed pressed the space bar key 7 times and then typed some words and then 5 spaces again and a word:
danny hi hello daniel hello
So lets say danny is after 7 spaces from the beginning in textBox1 and between daniel and hello there are more 5 spaces.
In my code i did:
if (string.IsNullOrEmpty(words[i]))
{
sb.Append(words[i]);
}
But that never will happen and its not right.
I wanted to check that if before or after a word in the textBox there is any space/s add the space/s to the sb variable.
So in the end textBox2 content will be the same as in textBox1 with the same number of spaces between the words.
Now textBox2 looks like a long one string of words without any spaces between them.
My problem is how to add the same spaces between the words from textBox1 ?
I simplified your code a little, but you should find it easy to apply in your situation. The problem comes from the fact that you are losing the spaces when you do the split and they are not being added back in. The solution is to use "String.Join" when you have the finished collection of strings. In this case since you know the output size is the same as the input size, I don't see any reason to use the stringbuilder. Just use an array you size to the input.
string inputText = "This is a test";
var words = inputText.Split(new char[] { ' ' });
var outputWords = new string[words.Length];
for (int i = 0; i < words.Length; i++)
{
if (string.IsNullOrEmpty(words[i]))
{
outputWords[i] = words[i];
}
else
{
outputWords[i] = Scramble(words[i]);
}
}
string outputText = string.Join(" ",outputWords);
This statement is absolutely useless:
if (string.IsNullOrEmpty(words[i]))
{
sb.Append(words[i]);
}
It seems you need something like this (not tested):
private void BtnScrambleText_Click(object sender, EventArgs e)
{
textBox1.Enabled = false;
BtnScrambleText.Enabled = false;
StringBuilder sb = new StringBuilder();
var words = Regex.Split(textBox1.Text, #"(?=(?<=[^\s])\s+)");
foreach (string word in words)
{
ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(word.Trim());
scrmbltb.GetText();
sb.Append(word.Replace(word.Trim(), scrmbltb.scrambledWord));
}
textBox2.AppendText(sb.ToString());
}
Regex.Split(textBox1.Text, #"(?=(?<=[^\s])\s+)") splits the input string with preserving spaces.
This the easy form
string text=mytextbox.Text;
while(text.Contains(" ")) //while two spaces
text=text.Replace(" "," "); //remove two spaces
If i got it right, your problem is to keep the exact number of spaces between the then scrambled words.
var words = string.Split(new char[]{' '}, StringSplitOptions.None); // this keeps the spaces as "epmty words"
var scrambled = words.Select(w => { if (String.IsNullOrEmpty(w))
return w;
else {
ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(w);
scrmbltb.GetText();
return scrmbltb.scrambledWord;
}
});
var result = string.Join(" ", scrambled);

c# splitting an array and displaying it in descending order in a textbox

I wish to display an array of text in a textbox, after splitting it with a comma, i pass a bunch of numbers into textbox1 and split it with the commas, how do i sort the number in descending order. here is the method i got so far
private void btnCalc_Click(object sender, EventArgs e)
{
//string A = txtInput.Text;
string[] arrText = txtInput.Text.Split(',');
int[] newOne = new int[]{};
foreach (string r in arrText)
{
}
txtOutput.AppendText( );
}
int[] newOne = arrText.Select(x => int.Parse(x)).OrderByDescending(x => x).ToArray();
You should be able to do it like this:
private void btnCalc_Click(object sender, EventArgs e)
{
//string A = txtInput.Text;
string[] arrText = txtInput.Text.Split(',');
txtOutput.Text = string.Join(",",arrText.Select( s => int.Parse(s)).OrderByDescending( i => i))
}
Note that this will blow up if some of the input text between the commas is not a number.
this should work:
var newOne = arrText.OrderByDescending(int.Parse).ToArray();
foreach (var s in newOne)
{
txtOutput.AppendText(s);
}

Categories