Automatic Editing of a string to remove spaces C# - c#

When I copy a string from an excel data set into the text box, the string has HUGE spaces in between each item in the string.
I currently have if (textBox1.Text.Contains(" ") == true) to detect the spaces in the string.
What would I use to delete those spaces?
Bonus Question: I do still need one space inbetween each item in the string, how would I add that and still delete the massive spaces?
private void radioGenerateScript_CheckedChanged(object sender, EventArgs e)
{
hexData.Cells.Copy();
textBox1.Clear();
textBox1.Paste();
if (textBox1.Text.Contains(" ") == true)
{
}
}
private void radioWriteScript_CheckedChanged(object sender, EventArgs e)
{
string waveForm = textBox1.Text;
System.IO.File.WriteAllText("E:/Scripts/Test.us1", waveForm);
}

If you want to remove all kinds of whitespaces use:
textBox1.Text = Regex.Replace(textBox1.Text, #"\s+", "");
\s matches all whitespaces (spaces, tabs and new lines).

textBox1.Text = Regex.Replace(textBox1.Text, " +", " ");
It seems that you have tabs as separators, so the following is better (as Alexei suggested):
textBox1.Text = Regex.Replace(textBox1.Text, #"\s+", " ");

textBox1.Text = textBox1.Text.Replace(" ", "");
If you want to keep some spaces then use Split and string.Join
var words = textBox1.Text.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
textBox1.Text = string.Join(" ", words);

Related

Preventing duplicate entries to excel

I'm creating a program in my free time to store info about my trading card collection. I was wondering is there any way to prevent duplicate entries into excel using the File.AppendAllText method. My current code is:
private void btnAdd_Click(object sender, EventArgs e)
{
Global.card.Add(new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text));
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
StringBuilder sb = new StringBuilder();
foreach (Card card in Global.card)
{
sb.AppendLine(card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType);
}
File.AppendAllText(file, sb.ToString());
MessageBox.Show("Card Added");
}
When I try to add more than one card, the data of the previous one is entered into the excel file so it appears twice when I don't want it to. Thanks
Try File.WriteAllText instead. File.AppendAllText will add the text to the bottom of the file.
Alternatively, you could do File.AppendAllLines for the card you are adding, like this:
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text)
Global.card.Add(card);
File.AppendAllLines(file, new[] {card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType});
MessageBox.Show("Card Added");
}
It looks that whenever you add single card you're appending all cards from Global.card, so I would get rid of foreach loop. You can just append this single card.
Try something like:
Card newCard = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text)
Global.card.Add(newCard)
File.AppendAllText(file, newCard.CardNo + delimiter + newCard.CardName + delimiter + newCard.CardRarity + delimiter + newCard.CardType);
You also don't need StringBuilder, but I would work on ToString method for your Card class.

Using \n correctly?

My code searches through a list and then if it finds a match, it displays the object in my listbox. My problem is that if there is more than 1 object in the list (if im searching for Alex and there is two objects with the name Alex), it returns it all on the same line instead of separating them to separate lines.
I coulda swore match += request + "\n"; was how to do it correctly, but it's not working.
Edit: One thing I dont understand is that if i just have match += request; it will allow me to use the horizontal scroll bar on my listbox to see everything written. And if i use match += request + "\n"; or match += request + Environment.NewLine; it doesn't let me use the scroll box and just cuts off.
public string SearchRequest(string keyword)
{
bool found = false;
string noMatch = "No requests with the name " + "'" + keyword + "'" + " were found";
string match = "";
foreach (ServiceRequest request in Requests)
{
if (request.searchKeywords(keyword))
{
match += request + "\n";
found = true;
}
}
if (found)
return match;
else
return noMatch;
}
/
public bool searchKeywords(string keyword)
{
if (keyword == name)
return true;
else
return false;
}
/
private void btnSearch_Click(object sender, EventArgs e)
{
lstSearch.Items.Clear();
lstSearch.Items.Add(myRequest.SearchRequest(txtSearch.Text));
}
Try
match += request + Environment.NewLine;
If you put all the results in a single string then it will still be a single item in the list.
Return an array of strings from the method instead of a single string:
public string[] SearchRequest(string keyword) {
List<string> match = new List<string>();
foreach (ServiceRequest request in Requests) {
if (request.searchKeywords(keyword)) {
match.Add(request.ToString());
}
}
if (match.Count > 0) {
return match.ToArray();
} else {
return new string[] { "No requests with the name " + "'" + keyword + "'" + " were found" };
}
}
Then use AddRange to add the strings as separate items in the list:
lstSearch.Items.AddRange(myRequest.SearchRequest(txtSearch.Text));
In Windows OS, the new line is two characters, the Carriage Return \r followed by Line Feed: \n. You can use Environment.NewLine as a shortcut (preferred) or append "\r\n" yourself. See further wikipedia entry on newline
Use one of these:
match += request + "\r\n";
Use an string literal:
match += request + #"
";
OR only at runtime will this resolve:
match += request + System.Environment.NewLine;
On Unix "\n"
You can't add a string with newlines to a listbox and expect it to show up as multiple items. Either split the string on newline and add each line separately to the listbox, or return a list of strings from your search function to begin with, avoiding the need for a split afterwards.

Split null or space on the first of a string?

I'm getting a string " abc df fd";
I want to split a space or null of string. As result is "abc df fd" That such I want;
private string _senselist;
public string senselist
{
get
{
return _senselist;
}
set
{
_senselist = value.Replace("\t", "").Replace(" "," ").Split(,1);
}
}
To remove spaces from the begining and the ending of a string, you can use Trim() method.
string data = " abc df fd";
string trimed = data.Trim(); // "abc df fd"
On your code add Trim at the end, instead of Split
_senselist = value.Replace("\t", "").Replace(" "," ").Trim();
As #andrei-rînea recommended you can also check TrimStart(' ') and TrimEnd(' ').

Reading txt file line by line than than write all lines to the RichTextBox

when i click to button it'll take these links from c:\text.txt file and it will write into my richtextbox
in my text.txt:
en.wikipedia.org/wiki/Extreme_programming
en.wikipedia.org/wiki/Boolean_algebra
en.wikipedia.org/wiki/Microsoft_Visual_Studio
en.wikipedia.org/wiki/Web_crawler
(there is no empty rows between links)
after that i want to call that links line by line into my other button to parse its html codes and write to other richtextbox
here is my parse button code:
private void button2_Click(object sender, EventArgs e)
{
string s = KaynakKodunuCek("http://tr.wikipedia.org/wiki/Lale");
// <p ... > </p> tagları arasını alıyor.(taglar dahil)
Regex regex = new Regex("<p[^>]*>.*?</p>");
string gelen = s;
string inside = null;
Match match = regex.Match(gelen);
if (match.Success)
{
inside = match.Value;
richTextBox3.Text = inside;
}
string outputStr = "";
foreach (Match ItemMatch in regex.Matches(gelen))
{
Console.WriteLine(ItemMatch);
inside = ItemMatch.Value;
//boşluk bırakıp alt satıra yazıyor
outputStr += inside + "\r\n";
}
richTextBox3.Text = outputStr;
}
here i want to call links string s = KaynakKodunuCek("here");
Or should i use listbox instead of richtextbox
Yes, listBox would be better.But if you want to do it with richTexBox you can use this:
string[] links = richTextBox2.Text.Split(new [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
for(int i=0;i<links.Length;i++)
{
string s = KaynakKodunuCek(links[i]);
...
}

RegEx -- getting rid of double whitespaces?

I have an app that goes in, replaces "invalid" chars (as defined by my Regex) with a blankspace. I want it so that if there are 2 or more blank spaces in the filename, to trim one. For example:
Deal A & B.txt after my app runs, would be renamed to Deal A   B.txt (3 spaces b/w A and B). What i want is really this: Deal A B.txt (one space between A and B).
I'm trying to determine how to do this--i suppose my app will have to run through all filenames at least once to replace invalid chars and then run through filenames again to get rid of extraneous whitespace.
Can anybody help me with this?
Here is my code currently for replacing the invalid chars:
public partial class CleanNames : Form
{
public CleanNames()
{
InitializeComponent();
}
public void Sanitizer(List<string> paths)
{
string regPattern = (#"[~#&$!%+{}]+");
string replacement = " ";
Regex regExPattern = new Regex(regPattern);
StreamWriter errors = new StreamWriter(#"S:\Testing\Errors.txt", true);
var filesCount = new Dictionary<string, int>();
dataGridView1.Rows.Clear();
try
{
foreach (string files2 in paths)
{
string filenameOnly = System.IO.Path.GetFileName(files2);
string pathOnly = System.IO.Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName);
if (!System.IO.File.Exists(sanitized))
{
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = pathOnly;
clean.Cells[1].Value = filenameOnly;
clean.Cells[2].Value = sanitizedFileName;
dataGridView1.Rows.Add(clean);
System.IO.File.Move(files2, sanitized);
}
else
{
if (filesCount.ContainsKey(sanitized))
{
filesCount[sanitized]++;
}
else
{
filesCount.Add(sanitized, 1);
}
string newFileName = String.Format("{0}{1}{2}",
System.IO.Path.GetFileNameWithoutExtension(sanitized),
filesCount[sanitized].ToString(),
System.IO.Path.GetExtension(sanitized));
string newFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(sanitized), newFileName);
System.IO.File.Move(files2, newFilePath);
sanitized = newFileName;
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = pathOnly;
clean.Cells[1].Value = filenameOnly;
clean.Cells[2].Value = newFileName;
dataGridView1.Rows.Add(clean);
}
}
}
catch (Exception e)
{
errors.Write(e);
}
}
private void SanitizeFileNames_Load(object sender, EventArgs e)
{ }
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
The problem is, that not all files after a rename will have the same amount of blankspaces. As in, i could have Deal A&B.txt which after a rename would become Deal A B.txt (1 space b/w A and B--this is fine). But i will also have files that are like: Deal A & B & C.txt which after a rename is: Deal A   B   C.txt (3 spaces between A,B and C--not acceptable).
Does anybody have any ideas/code for how to accomplish this?
Do the local equivalent of:
s/\s+/ /g;
Just add a space to your regPattern. Any collection of invalid characters and spaces will be replaced with a single space. You may waste a little bit of time replacing a space with a space, but on the other hand you won't need a second string manipulation call.
Does this help?
var regex = new System.Text.RegularExpressions.Regex("\\s{2,}");
var result = regex.Replace("Some text with a lot of spaces, and 2\t\ttabs.", " ");
Console.WriteLine(result);
output is:
Some text with a lot of spaces, and 2 tabs.
It just replaces any sequence of 2 or more whitespace characters with a single space...
Edit:
To clarify, I would just perform this regex right after your existing one:
public void Sanitizer(List<string> paths)
{
string regPattern = (#"[~#&$!%+{}]+");
string replacement = " ";
Regex regExPattern = new Regex(regPattern);
Regex regExPattern2 = new Regex(#"\s{2,}");
and:
foreach (string files2 in paths)
{
string filenameOnly = System.IO.Path.GetFileName(files2);
string pathOnly = System.IO.Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
sanitizedFileName = regExPattern2.Replace(sanitizedFileName, replacement); // clean up whitespace
string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName);
I hope that makes more sense.
you can perform another regex replace after your first one
#" +" -> " "
As Fosco said, with formatting:
while (mystring.Contains(" ")) mystring = mystring.Replace(" "," ");
// || || |
After you're done sanitizing it your way, simply replace 2 spaces with 1 space, while 2 spaces exist in the string.
while (mystring.Contains(" ")) mystring = mystring.Replace(" "," ");
I think that's the right syntax...

Categories