How to split a string by using more than one delimiter - vb.net

Below a script I used in my SSIS package.
If (Row.AnswerType.Trim().ToUpper = "MULTIPLE SELECT" And _
Row.SurveyQuestionID = Row.SurveyDefinitionDetailQuestionNumber) Then
Dim Question1 As String = Row.SurveyDefinitionDetailAnswerChoices.ToUpper.Trim()
Dim ans1 As String = Row.SurveyAnswer.ToUpper.Trim()
For Each x As String In ans1.Split(New [Char]() {CChar(vbTab)})
If Question1.Contains(x) Then
Row.IsSkipped = False
Else
Row.IsSkipped = True
'Row.IsAllowed = True
Row.ErrorDesc = "Invalid Value in Answer Column For Multiple Select!"
End If
Next
End If
This script only succeeds when having a tab as delimiter. But I need both tab and non tab characters as delimiters.

Add all the needed characters to the character array
ans1.Split(New [Char]() { CChar(vbTab), CChar(" "), CChar(";") })
Or
ans1.Split(New [Char]() { CChar(vbTab), " "C, ";"C })
by using the character literal suffix C.

Related

String.Replace() for quotation marks

I am trying to run the following line of code to replace the Microsoft Word quotes with ones our database can store. I need to work around users copying strings from Microsoft Word into my textareas.
instrText = instrText.Replace("“", """).Replace("”", """)
I am getting syntax errors for the number of arguments.
I have tried character escapes and a couple other ways of formatting the arguments with no luck.
This changes the 'smart' quotes from word,
'non standard quotes
Dim Squotes() As Char = {ChrW(8216), ChrW(8217)} 'single
Dim Dquotes() As Char = {ChrW(8220), ChrW(8221)} 'double
'build test string
Dim s As String = ""
For x As Integer = 0 To Squotes.Length - 1
s &= x.ToString & Squotes(x) & ", "
Next
For x As Integer = 0 To Dquotes.Length - 1
s &= (x + Squotes.Length).ToString & Dquotes(x) & ", "
Next
'replace
For Each c As Char In Squotes
s = s.Replace(c, "'"c)
Next
For Each c As Char In Dquotes
s = s.Replace(c, ControlChars.Quote)
Next
Try the following:
Private Function CleanInput(input As String) As String
DisplayUnicode(input)
'8216 = &H2018 - left single-quote
'8217 = &H2019 - right single-quote
'8220 = &H201C - left double-quote
'8221 = &H201D - right double-quote
'Return input.Replace(ChrW(&H2018), Chr(39)).Replace(ChrW(&H2019), Chr(39)).Replace(ChrW(&H201C), Chr(34)).Replace(ChrW(&H201D), Chr(34))
Return input.Replace(ChrW(8216), Chr(39)).Replace(ChrW(8217), Chr(39)).Replace(ChrW(8220), Chr(34)).Replace(ChrW(8221), Chr(34))
End Function
Private Sub DisplayUnicode(input As String)
For i As Integer = 0 To input.Length - 1
Dim lngUnicode As Long = AscW(input(i))
If lngUnicode < 0 Then
lngUnicode = 65536 + lngUnicode
End If
Debug.WriteLine(String.Format("char: {0} Unicode: {1}", input(i).ToString(), lngUnicode.ToString()))
Next
Debug.WriteLine("")
End Sub
Usage:
Dim cleaned As String = CleanInput(TextBoxInput.Text)
Resources:
ASCII table
C# How to replace Microsoft's Smart Quotes with straight quotation marks?
How to represent Unicode character in VB.Net String literal?
Note: Also used Character Map in Windows.
You have a solution that works above, but in keeping with your original form:
instrText = instrText.Replace(ChrW(8220), """"c).Replace(ChrW(8221), """"c)

Substring Method in VB.Net

I have Textboxes Lines:
{ LstScan = 1,100, DrwR2 = 0000000043 }
{ LstScan = 2,200, DrwR2 = 0000000041 }
{ LstScan = 3,300, DrwR2 = 0000000037 }
I should display:
1,100
2,200
3,300
this is a code that I can't bring to a working stage.
Dim data As String = TextBox1.Lines(0)
' Part 1: get the index of a separator with IndexOf.
Dim separator As String = "{ LstScan ="
Dim separatorIndex = data.IndexOf(separator)
' Part 2: see if separator exists.
' ... Get the following part with Substring.
If separatorIndex >= 0 Then
Dim value As String = data.Substring(separatorIndex + separator.Length)
TextBox2.AppendText(vbCrLf & value)
End If
Display as follows:
1,100, DrwR2 = 0000000043 }
This should work:
Function ParseLine(input As String) As String
Const startKey As String = "LstScan = "
Const stopKey As String = ", "
Dim startIndex As String = input.IndexOf(startKey)
Dim length As String = input.IndexOf(stopKey) - startIndex
Return input.SubString(startIndex, length)
End Function
TextBox2.Text = String.Join(vbCrLf, TextBox1.Lines.Select(AddressOf ParseLine))
If I wanted, I could turn that entire thing into a single (messy) line... but this is more readable. If I'm not confident every line in the textbox will match that format, I can also insert a Where() just before the Select().
Your problem is you're using the version of substring that takes from the start index to the end of the string:
"hello world".Substring(3) 'take from 4th character to end of string
lo world
Use the version of substring that takes another number for the length to cut:
"hello world".Substring(3, 5) 'take 5 chars starting from 4th char
lo wo
If your string will vary in length that needs extracting you'll have to run another search (for example, searching for the first occurrence of , after the start character, and subtracting the start index from the newly found index)
Actually, I'd probably use Split for this, because it's clean and easy to read:
Dim data As String = TextBox1.Lines(0)
Dim arr = data.Split()
Dim thing = arr(3)
thing now contains 1,100, and you can use TrimEnd(","c) to remove the final comma
thing = thing.TrimEnd(","c)
You can reduce it to a one-liner:
TextBox1.Lines(0).Split()(3).TrimEnd(","c)

VB.NET - Delete excess white spaces between words in a sentence

I'm a programing student, so I've started with vb.net as my first language and I need some help.
I need to know how I delete excess white spaces between words in a sentence, only using these string functions: Trim, instr, char, mid, val and len.
I made a part of the code but it doesn't work, Thanks.
enter image description here
Knocked up a quick routine for you.
Public Function RemoveMyExcessSpaces(str As String) As String
Dim r As String = ""
If str IsNot Nothing AndAlso Len(str) > 0 Then
Dim spacefound As Boolean = False
For i As Integer = 1 To Len(str)
If Mid(str, i, 1) = " " Then
If Not spacefound Then
spacefound = True
End If
Else
If spacefound Then
spacefound = False
r += " "
End If
r += Mid(str, i, 1)
End If
Next
End If
Return r
End Function
I think it meets your criteria.
Hope that helps.
Unless using those VB6 methods is a requirement, here's a one-line solution:
TextBox2.Text = String.Join(" ", TextBox1.Text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))
Online test: http://ideone.com/gBbi55
String.Split() splits a string on a specific character or substring (in this case a space) and creates an array of the string parts in-between. I.e: "Hello There" -> {"Hello", "There"}
StringSplitOptions.RemoveEmptyEntries removes any empty strings from the resulting split array. Double spaces will create empty strings when split, thus you'll get rid of them using this option.
String.Join() will create a string from an array and separate each array entry with the specified string (in this case a single space).
There is a very simple answer to this question, there is a string method that allows you to remove those "White Spaces" within a string.
Dim text_with_white_spaces as string = "Hey There!"
Dim text_without_white_spaces as string = text_with_white_spaces.Replace(" ", "")
'text_without_white_spaces should be equal to "HeyThere!"
Hope it helped!

Replace word with the same amount of spaces

How can I replace a word (p.g in ListBox) with the same number of spaces (as letters)?
You can use the string constructor:
dim s as string = "1234"
s = New String(" ", s.length)
With a listbox, you might want to consider removing the item instead of setting it to spaces:
ListBox1.Items.RemoveAt(i)
Here's one way to remove an arbitrary word from a string s:
sRemove = "abc"
i = s.IndexOf(sRemove)
If i >= 0 Then s = s.Substring(0, i) & New String(" ", sRemove.Length) & s.Substring(i + sRemove.Length)

string.split vb.net

I have a text in database which is "computer-hardware". I used that code to split
' string seperated by colons '-'
Dim info As String = strcotegory
Dim arInfo As String() = New String(3) {}
' define which character is seperating fields
Dim splitter As Char() = {"-"c}
arInfo = info.Split(splitter)
For x As Integer = 0 To arInfo.Length - 1
Response.Write(arInfo(x) & "</br> ")
Next
but now I want to get "computer" in textbox1 and "hardware" in textbox2.
please guide me
If I understood you correctly, replace the For loop with the following lines of code:
textbox1.Text = arInfo(0)
textbox2.Text = arInfo(1)
By the way, initializing arInfo (... = New String(3) {}) is not necessary, since you overwrite the value of arInfo anyway (arInfo = ...).