String.Replace() for quotation marks - vb.net

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)

Related

Using Ms Access VBA, how do I check the value of a variable to see if it has a value other than "', "

I have a variable with a string...and I want to know if it contains any value other than single quote, comma and a space ("', ") I'm using vba in excel.
for example, i have a varible strA = "'test', 'player'"
I want to check to see if strA has any characters other than "', " (single quote, comma and space).
Thanks
Here is a strategy based on Count occurrences of a character in a string
I don't have vba handy, but this should work. The idea is to remove all these characters and see if anything is left. text represents your string that is being tested.
Dim TempS As String
TempS = Replace(text, " " , "")
TempS = Replace(TempS, "," , "")
TempS = Replace(TempS, "'" , "")
and your result is Len(TempS>0)
Another approach is to use recursion by having a base case of false if the string is empty, if the first character is one of the three call ourselves on the rest of the string, or if not the value is true. Here is the code
function hasOtherChars(s As String) As Boolean
hasOtherChars=false
if (len(s)=0) then
exit function
end if
Dim asciiSpace As Integer
asciiSpace = Asc(" ")
Dim asciiComma As Integer
asciiComma= Asc(",")
Dim asciiApostrophe As Integer
asciiApostrophe = Asc("'")
Dim c as Integer
c = Asc(Mid$(s, 1, 1))
if ((c=asciiSpace) or (c=asciiComma) or (c=asciiApostrophe)) then
hasOtherChars = hasOtherChars(Mid$(s,2))
else
hasOtherChars=true
end if
End function
Again I am borrowing from the other thread.

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!

Substitute wildcard characters (? and *) in Excel 2010 vba macro

Using a macro in Excel 2010, I am trying to replace all "invalid" characters (as defined by a named range) with spaces.
Dim sanitisedString As String
sanitisedString = Application.WorksheetFunction.Clean(uncleanString)
Dim validCharacters As Range
Set validCharacters = ActiveWorkbook.Names("ValidCharacters").RefersToRange
Dim pos As Integer
For pos = 1 To Len(sanitisedString)
If WorksheetFunction.CountIf(validCharacters, Mid(sanitisedString, pos, 1)) = 0 Then
sanitisedString = WorksheetFunction.Replace(sanitisedString, pos, 1, " ")
End If
Next
It works for all characters except * and ?, because CountIf is interpreting those as wildcard characters.
I have tried escaping all characters in the CountIf, using:
If WorksheetFunction.CountIf(validCharacters, "~" & Mid(sanitisedString, pos, 1)) = 0
but this led to all characters being replaced, regardless of whether they are in the list or not.
I then tried doing two separate Substitute commands, placed after the for loop using "~*" and "~?":
sanitisedString = WorksheetFunction.Substitute(sanitisedString, "~*", " ")
sanitisedString = WorksheetFunction.Substitute(sanitisedString, "~?", " ")
but the * and ? still make it through.
What am I doing wrong?
Since there are onlyl two wildcards to worry about, you can test for those explicitly:
Dim character As String
For pos = 1 To Len(sanitisedString)
character = Mid(sanitisedString, pos, 1)
If character = "*" Or character = "?" Then character = "~" & character
If WorksheetFunction.CountIf(validCharacters, character) = 0 Then
Mid$(sanitisedString, pos, 1) = " "
End If
Next

Variable truncates when using messagebox

I have a strange problem here. In my code, variable b string, has the value "Test Test Test". This value we can see while debugging the variable as well as in the text visualizer.
Now the problem is, if I show the same string using Messagebox, the value is just "Test". What can I do here to get the complete value.
I am converting from an ebcdic encoded bytes to corresponding utf8 string and doing the above operation. Any thoughts. below is my sample code.
Dim hex As String = "e385a2a300000000e385a2a3000000e385a2a3"
Dim raw As Byte() = New Byte((hex.Length / 2) - 1) {}
Dim i As Integer
For i = 0 To raw.Length - 1
raw(i) = Convert.ToByte(hex.Substring((i * 2), 2), &H10)
Next i
Dim w As String = System.Text.Encoding.GetEncoding(37).GetString(raw)
Dim raw1 As Byte() = Encoding.UTF8.GetBytes(w)
Dim b As String = Encoding.UTF8.GetString(raw1)
MessageBox.Show(b)
Look at the byte array. You have 4 ASCII 0's after each "Test". ASCII character code 0 corresponds to nul, which is a string termination sequence. If you want spaces instead of nulls there...
Dim b As String = Encoding.UTF8.GetString(raw1).Replace(Chr(0), " ")
It is possible that the string "b" might contains some control character.
To test a control char in string.
For Each p As Char In b
MsgBox(p & " " & Char.IsControl(p) & " " & AscW(p))
Next
Use String#Replace to replace control chars.
b = b.Replace(ChrW(0), " ")
MsgBox(b)

Trim last "," delimiter of a string in VB.NET

This is my code:
With ad.Tables(2)
For i As Integer = 0 To .Rows.Count - 1
If .Rows(i)("name") & "" <> "" Then
temp &= .Rows(i)("name") & ", "
End If
Next
End With
temp = temp.Trim(",")
testing &= "&Name=" & temp & vbCrLf
With this is get a comma in the end of the string. But if I do
temp = temp.Trim.Trim(",")
all commas are deleted.
How do I keep all commas and only delete the last one?
temp = temp.TrimEnd(CChar(","))
That will do it and I think it is the easiest way.
temp = temp.Trim().Substring(0, temp.Length - 1)
or
temp = temp.Trim().Remove(temp.Length - 1)
You can avoid the Trim/extra character if you set a delimiter within the loop
Dim delimiter as string = ""
For i As Integer = 0 To .Rows.Count - 1
If .Rows(i)("name") & "" <> "" Then
temp &= delimiter & .Rows(i)("name")
delimiter = ","
End If
Next
The Trim() function has a Char() (static array of characters) parameter on it, you don't need to pass a Char explicitly.
' VB.Net Version
", Hello ^_^ ^_^ ,,, , ,, ,, ,".Trim({" "c, ","c})
//C# version
", Hello ^_^ ^_^ ,,, , ,, ,, ,".Trim({' ', ','})
Would produce the output
"Hello ^_^ ^_^"
The multi-parameter .Trim() removes the specified characters from both the beginning and the end of the string. If you want to only trim out the beginning or the end, use .TrimStart() or .TrimEnd() respectively.
This works:
dim AlarmStr as string="aaa , bbb , ccc , "
AlarmStr = AlarmStr.Remove(AlarmStr.LastIndexOf(","))
Check to see if the loop is done before adding the last comma. #cleaner
While dr.Read
For c As Integer = 0 To dr.FieldCount - 1
s.Append(dr(c).ToString.Trim)
'This line checks if the loop is ending before adding a comma
If (c < dr.FieldCount - 1) Then s.Append(",")
Next
s.Append(vbCrLf)
End While
I wonder, that based on the OP's code sample, nobody suggested to use String.Join or build an output with StringBuilder
Dim names As New List(Of String)
With ad.Tables(2)
For i As Integer = 0 To .Rows.Count - 1
' DataRow("columnName").ToString() returns value or empty string if value is DbNull
If .Rows(i)("name").ToString() <> "" Then
names.Add(.Rows(i)("name"))
End If
Next
End With
Dim temp As String = String.Join(", ", names)
testing &= "&Name=" & temp & vbCrLf
With LINQ and DataRow extension method .Field(Of T) code will look simpler
Dim names = ad.Tables(2).
AsEnumerable().
Select(row => row.Field<String>("name")).
Where(name => String.IsNullOrEmpty(name) = False)
Dim temp As String = String.Join(", ", names)
testing &= "&Name=" & temp & vbCrLf
If you go further you can(should) use StringBuilder for building a string and use Aggregate method to build string from the collection
I know that a little bit odd, but I found this works for me:
Visual Basic:
Every time: mystring = "today, I love go out , , , ," (less than five commas and spaces)
mystring.Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",")
temp = temp.TrimEnd()
this trims the trailing spaces from a string.