Split method with line breaker vb.net - vb.net

I have a checkedlistbox to fill with the textbox values, but i have some issues cause if i paste the text from the textbox in a word file it comes with linebreakers, and not just spaces . Maybe that's why the checked list box is not being filled properly.
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
Dim separated = TextBox2.Text.Split(vbNewLine & " ")
CheckedListBox1.Items.Clear()
CheckedListBox1.Items.AddRange(separated)
CheckedListBox1.Items.Remove(vbCrLf)
CheckedListBox1.Items.Remove("#")
CheckedListBox1.Items.Remove("PI")
End Sub
How can i get rid of this problem? If i paste the values in word they come like this:

You are currently separating the string where a space is followed by a new line. Any other spaces around this string are included in the output. You want to use a different version of Split, listing each character, so that ANY of those characters can be used to split the string:
Dim separated = TextBox2.Text.Split(vbCr, vbLf, vbTab, " "c)
This will treat one or more of space, tab, line feed OR carriage return as a split and will not include any of them in the strings it returns. It will however return a number of empty strings, so you will need to add the strings individually, filtering these out. The rest of the code can be replaced by this:
CheckedListBox1.Items.Clear()
For Each item In separated
If item <> "" Then CheckedListBox1.Items.Add(item)
Next

Get rid of all spaces and then split
Dim separated = TextBox2.Text.Replace(" ", "").Split(vbNewLine)
UPDATE to remove the tabs
char tabs = '\u0009';
Dim separated = TextBox2.Text.Replace(" ", "").Replace(tabs, "").Split(vbNewLine)
You need to remove all items that are not required prior to splitting.
SO... based on your example
char tabs = '\u0009';
StrippedText = TextBox2.Text.Replace(" ", "").Replace(tabs, "").Replace("P1" & vbCRLF & vbCRLF, "").Replace(vbCRLF & "#" & vbCRLF, "")
Dim separated = StrippedText.Split(vbNewLine)

Related

Removing a Duplicate Item from ListBox converted into a string

I have an issue where, when I take the items from my ListBox, and convert them into a single-line string, it duplicates the last item. My goal is for it to take just the items from the ListBox, and convert it into a single line of text, seperated by commas (,).
It took me a while, but I found some code on this thread, and it works for the most part, but the last item is always duplicated when converted to a string. The code that I am using is:
Dim item As Object
Dim List As String
' Other unrelated code
' Credit: T0AD - https://www.tek-tips.com/viewthread.cfm?qid=678275
For Each item In Form1.ListBox1_lstbox.Items
List &= item & ","
Next
'To remove the last comma.
List &= item.SubString(0, item.Length - 0)
' This is weird, but setting item.Length - 1 actually removes two characters.
' Add text to textbox
TextBox1.Text = List
I have a feeling that it has to deal with the code that removes the comma, as it is an &= that calls the item Dim again. But I can't seem to figure out what to do.
An example of the output would be something like this: Item1,Item2,Item3,Item3
When I just want this: Item1,Item2,Item3
Your problem is with this line.
List &= item.SubString(0, item.Length - 0)
You are adding another string to List with the &=. The string you are adding is the final value of item from the For Each loop.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ListBox1.Items.Count = 0 Then
MessageBox.Show("There are no items in the list box.")
Exit Sub
End If
Dim List As String = ""
For Each item In ListBox1.Items
List &= item.ToString & ","
Next
List = List.Substring(0, List.Length - 1)
TextBox1.Text = List
End Sub
Additional solution provided by #Andrew Morton in comments, which doesn't require the ListBox to contain items.
TextBox1.Text = String.Join(",", ListBox1.Items.Cast(Of Object))

String Concatenation with Comma and Single Quotes E.g. ('ABC','DEF','GHI,'JKL')

I've been searching on internet how to Concatenate/Join Single quotes and comma on the String in vb.net's RichTextBox control. Example ('ABC','DEF','GHI,'JKL') I found this code online today it works even there's leading and trailing spaces and even lines are removed but the (' and ') are missing. Can you guys modify the code?
Code:
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text.Trim, "\s+", "','")
Inside the RichTextBox1
ABC
DEF
GHI
JKL
Result: ABC','DEF','GHI','JKL
Desired Result: ('ABC','DEF','GHI','JKL')
As you can see, there are multiple ways this could be done. Here's another:
myRichTextBox.Text = $"('{String.Join("'," & ControlsChars.Lf & "'", myRichTextBox.Lines)}')"
Note that I have used ControlChars.Lf where I would usually use Environment.NewLine because the RichTextBox always uses that line break. I assume that it has something to do with the RTF format and compatibility.
Give this a try
' starting RichTextBox1 contains
' ABC
' DEF
' GHI
' JKL
Dim lns() As String = RichTextBox1.Lines
For x As Integer = 0 To lns.Length - 1
lns(x) = String.Format("'{0}',", lns(x))
Next
lns(0) = "(" & lns(0)
lns(lns.Length - 1) = lns(lns.Length - 1).TrimEnd(","c)
lns(lns.Length - 1) &= ")"
RichTextBox1.Lines = lns
Not knowing how many lines you are dealing with in a real scenario, I chose to use a StringBuilder. It creates mutable (changeable) strings saving us throwing away and recreating strings many times.
Start off the sb with the initial "(". Then the loop uses an interpolated string with an embedded variable for each line. AppendLine will add a new line after the text.
Lastly we display the new string. In .net we can string the dot notation working left to right. First convert the StringBuilder back to an actual String with .ToString. Next we clean up the end of the new string by removing the final comma and the final new line. A new line is actually composed of 2 Chars, carriage return and line feed. Lastly I added the final ")"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines() = File.ReadAllLines("some text file path")
Dim sb As New StringBuilder
sb.Append("(")
For Each line In lines
sb.AppendLine($"'{line}',")
Next
RichTextBox1.Text = sb.ToString.Trim({","c, Convert.ToChar(13), Convert.ToChar(10)}) & ")"
End Sub

How to remove and re-add a comma in a string?

I have a textbox on my form that when a button is clicked, it is populated with numbers that are separated by a comma. I have a delete button that will remove the numbers with the comma one at a time. My question is how would I go about re-adding the comma every time i hit the add button, again? I thought i could add the comma in the beginning in an if statement, but its adding two commas, every time I hit the add button, if I delete, then try to re- add.
here is what i have :
if textbox1.text = "" then
textbox1.text = textbox1.text & testNumber(combobox.selecteditem) & ","
else
textbox1.text = "," & textbox1.text & testnumber(combox.selecteditem)
end if
The contents of the textbox should only be a view of a more appropriate underlying data structure. For example, you might have a List(Of Integer) or Queue(Of Integer) as a member of your form. When you add or remove an item you first update the collection, then you set the text. For example:
Add:
MyList.Add(nextNumber)
textbox1.text = String.Join(","c, MyList)
Remove:
MyList.RemoveAt(MyList.Count - 1);
textbox1.text = String.Join(","c, MyList)
Do this even if they want the ability to update the textbox directly. It's just in this case you must also be able to validate and parse the contents of the textbox to recreate the list.
First of all, storing numbers in a comma delimited string is pretty strange requirement. I'd suggest to store numbers in a proper data type, such as: List(Of Integer).
Assuming that testnumber function returns integer...
'define at the top of Form's module:
Private myNumbers As List(Of Integer) = New List(Of Integer)()
'copy-paste below method to the form's module
Private Function GetCommaSeparatedNumbers() As String
Return String.Join(",", myNumbers)
End Function
'finally:
'to add number
myNumbers.Add(testnumber(combox.selecteditem))
'to remove number
myNumbers.Remove(testnumber(combox.selecteditem))
'to display numbers
Me.textbox1.Text = GetCommaSeparatedNumbers()
If you would like to check out if number already exists on the list, use:
If myNumbers.Contains(testnumber(combox.selecteditem)) Then
'display warning
Else
'add number
End If
Good luck!
Your code is initial testing textbox1.Text = "" and then, if that is true, it is then doing textbox1.Text = textbox1.Text & testNumber(combobox.SelectedItem) & ",", but since textbox1.Text is "" this is the equivalent of:
textbox1.Text = "" & testNumber(combobox.SelectedItem) & ","
That really means you are adding a comma when you only have one number.
This is what you should be doing:
if textbox1.Text = "" then
textbox1.Text = testNumber(combobox.SelectedItem)
else
textbox1.Text = textbox1.Text & "," & testnumber(combox.SelectedItem)
end if
To add a number, I'd do it with this line:
TextBox1.AppendText(If(TextBox1.TextLength = 0, "", ",") & testNumber(ComboBox.SelectedItem))
Are numbers being deleted from the beginning or end?...or is a "selected" number from anywhere in the list being deleted?

Cleaning text strings in vb

I am trying to clean up a string from a text field that will be part of sql query.
I have created a function:
Private Function cleanStringToProperCase(dirtyString As String) As String
Dim cleanedString As String = dirtyString
'removes all but non alphanumeric characters except #, - and .'
cleanedString = Regex.Replace(cleanedString, "[^\w\.#-]", "")
'trims unecessary spaces off left and right'
cleanedString = Trim(cleanedString)
'replaces double spaces with single spaces'
cleanedString = Regex.Replace(cleanedString, " ", " ")
'converts text to upper case for first letter in each word'
cleanedString = StrConv(cleanedString, VbStrConv.ProperCase)
'return the nicely cleaned string'
Return cleanedString
End Function
But when I try to clean any text with two words, it strips ALL white space out. "daz's bike" becomes "Dazsbike". I am assuming I need to modify the following line:
cleanedString = Regex.Replace(cleanedString, "[^\w\.#-]", "")
so that it also lets single white space characters remain. Advice on how to do so is greatly received as I cannot find it on any online tutorials or on the MSDN site (http://msdn.microsoft.com/en-us/library/844skk0h(v=vs.110).aspx)
Use "[^\w\.,#\-\' ]" instead of your pattern string.
Also, I would use
Regex.Replace(cleanedString, " +", " ")
instead of
Regex.Replace(cleanedString, " ", " ")
Or, if you are not a big fan of regex...
Private Function cleanStringToProperCase(dirtyString As String) As String
'specify valid characters
Dim validChars As String = " #-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
'removes all but validChars'
Dim cleanedString As String = dirtyString.Where(Function(c) validChars.Contains(c)).ToArray
Dim myTI As Globalization.TextInfo = New Globalization.CultureInfo(Globalization.CultureInfo.CurrentCulture.Name).TextInfo
'return the nicely cleaned string'
Return myTI.ToTitleCase(cleanedString.Trim)
End Function

Get only the line of text that contains the given word VB2010.net

I have a text file on my website and I download the whole string via webclient.downloadstring.
The text file contains this :
cookies,dishes,candy,(new line)
back,forward,refresh,(new line)
mail,media,mute,
This is just an example it's not the actual string , but it will do for help purposes.
What I want is I want to download the whole string , find the line that contains the word that was entered by the user in a textbox, get that line into a string, then I want to use the string.split with as delimiter the "," and output each word that is in the string into an richtextbox.
Now here is the code that I have used (some fields are removed for privacy reasons).
If TextBox1.TextLength > 0 Then
words = web.DownloadString("webadress here")
If words.Contains(TextBox1.Text) Then
'retrieval code here
Dim length As Integer = TextBox1.TextLength
Dim word As String
word = words.Substring(length + 1) // the plus 1 is for the ","
Dim cred() As String
cred = word.Split(",")
RichTextBox1.Text = "Your word: " + cred(0) + vbCr + "Your other word: " + cred(1)
Else
MsgBox("Sorry, but we could not find the word you have entered", MsgBoxStyle.Critical)
End If
Else
MsgBox("Please fill in an word", MsgBoxStyle.Critical)
End If
Now it works and no errors , but it only works for line 1 and not on line 2 or 3
what am I doing wrong ?
It's because the string words also contains the new line characters that you seem to be omitting in your code. You should first split words with the delimiter \n (or \r\n, depending on the platform), like this:
Dim lines() As String = words.Split("\n")
After that, you have an array of strings, each element representing a single line. Loop it through like this:
For Each line As String In lines
If line.Contains(TextBox1.Text) Then
'retrieval code here
End If
Next
Smi's answer is correct, but since you're using VB you need to split on vbNewLine. \n and \r are for use in C#. I get tripped up by that a lot.
Another way to do this is to use regular expressions. A regular expression match can both find the word you want and return the line that contains it in a single step.
Barely tested sample below. I couldn't quite figure out if your code was doing what you said it should be doing so I improvised based on your description.
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub ButtonFind_Click(sender As System.Object, e As System.EventArgs) Handles ButtonFind.Click
Dim downloadedString As String
downloadedString = "cookies,dishes,candy," _
& vbNewLine & "back,forward,refresh," _
& vbNewLine & "mail,media,mute,"
'Use the regular expression anchor characters (^$) to match a line that contains the given text.
Dim wordToFind As String = TextBox1.Text & "," 'Include the comma that comes after each word to avoid partial matches.
Dim pattern As String = "^.*" & wordToFind & ".*$"
Dim rx As Regex = New Regex(pattern, RegexOptions.Multiline + RegexOptions.IgnoreCase)
Dim M As Match = rx.Match(downloadedString)
'M will either be Match.Empty (no matching word was found),
'or it will be the matching line.
If M IsNot Match.Empty Then
Dim words() As String = M.Value.Split(","c)
RichTextBox1.Clear()
For Each word As String In words
If Not String.IsNullOrEmpty(word) Then
RichTextBox1.AppendText(word & vbNewLine)
End If
Next
Else
RichTextBox1.Text = "No match found."
End If
End Sub
End Class