Can someone please tell me a way (or similar) to use (") in a text in vb.
eg. msgbox("some text here "other text here" more text" & vbnewline & "next line of text").
If you still dont get what I mean, all I need is this section ("other text") including the (") to show in a msgbox.
Either escape the quote by another quote Dim q as String = """" would be one quote, or use ControlChars.Quote
All you have to do is use double quotes.
For example : Dim abc as string = "Using double ""quotes""
So for MsgBox you would do the same. MsgBox("Use double ""quotes"" to show quotes")
Escaping the quotes never looks quite right to me.
I like using a fluent-ish API instead:
<Extension>
Public Function Quote(byval value as String) As String
Return value & CHR(34)
End Function
<Extension>
Public Function SurroundWith(ByVal value As String, ByVal surround As String) As String
Return surround & value & surround
End Function
Usage:
Console.WriteLine("Hello there! I'm Bob ".Quote & "Buddy".Quote & " Holly.")
Console.WriteLine("Hello there! I'm Bob " & "Buddy".SurroundWith(CHR(34)) & " Holly.")
Related
I have an embedded text file as a Resource. The content is:
Apple
Pear
Orange
I am trying to pull this into a List(Of String) but the Carriage Return and Line Feed characters are messing it up.
For example I try this:
Dim myNames As List(Of String) = My.Resources.TreeNames.Split(CChar(vbCrLf)).ToList
But the line feed character is being passed through:
"Apple"
vbLf & "Pear"
vbLf & "Orange"
so I try it using the environment variable:
Dim myNames As List(Of String) = My.Resources.TreeNames.Split(CChar(Environment.NewLine)).ToList
But that results in the exact same output.
So I try splitting it on the line feed character:
Dim myNames As List(Of String) = My.Resources.TreeNames.Split(CChar(vbLf)).ToList
And now the carriage return character is being passed through:
"Apple" & vbCr
"Pear" & vbCr
"Orange"
So the only way I got this to work is by first replacing the vbCr with nothing then splitting on the left over vbLf:
Dim myNames As List(Of String) = Replace(My.Resources.TreeNames, vbCr, "").Split(CChar(vbLf)).ToList
Can anyone explain why? If I pull the file in directly to a string using this:
Dim myNames as String = My.Resources.TreeNames
I get:
"Apple" & vbCrLf & "Pear" & vbCrLf & "Orange"
Why is split not working properly?
See the Docs about CChar(<expression>):
Any valid Char or String expression; only first character of a String
is converted; value can be 0 through 65535 (unsigned)
So CChar(vbCrLf) returns just VbCr (\r - &H0D)
Since you're now splitting the source string on just VbCr, the Line Feed, VbLf (\n - &H0A), remains.
You need the overload of String.Split() that accepts an array of Strings or Chars:
Note that vbCrLf is a String Type, so are VbCr and VbLf
Dim res = My.Resources.TreeNames
' As an array of String
Dim myNames = res.Split({vbCrLf}, StringSplitOptions.RemoveEmptyEntries).ToList()
'Or
Dim myNames = res.Split({vbCr, VbLf}, StringSplitOptions.RemoveEmptyEntries).ToList()
Or as an array of Chars:
Dim myNames = res.Split(vbCrLf.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList()
' Or
Dim myNames = res.Split({ChrW(13), ChrW(10)}, StringSplitOptions.RemoveEmptyEntries).ToList()
StringSplitOptions.RemoveEmptyEntries is used to remove empty lines generated by splitting on multiple contiguous chars.
Without it, using your sample string - 3 items separated by Carriage Return + Line Feed - you would get an array of 5 elements instead of 3, including 2 empty elements.
I would not recommend using the VB constants. Instead, you should be using the Environment.NewLine property: https://learn.microsoft.com/en-us/dotnet/api/system.environment.newline
Per the documentation:
The property value of NewLine is a constant customized specifically
for the current platform and implementation of the .NET Framework.
Usage:
Dim myNames = My.Resources.TreeNames.Split(Environment.NewLine)
Of course, you could skip .Split altogether and just
Dim LinesList = File.ReadAllLines("txtFruit.txt").ToList
With Option Infer on hold your cursor over LinesList and you will see that it is a strongly typed List(Of String)
I wish to remove spaces from lines that doesn't contain text, but not remove the line. Since a space character can be hard to identify, I will replace the space character with the "#" (hastag character) to showcase the example easier. The string looks something like this:
"This is
########a long string
with many lines
#######
and the above is empty
####this is empty
#############
#######hello"
I wish that the output would remove the spaces on the lines that only contains the space character. I am still using the "#" (hastag character) to showcase the spaces. The final output should look like this:
"This is
########a long string
with many lines
and the above is empty
####this is empty
#######hello"
Without the hashtag character acting as the space character, the expected output should look like this:
"This is
a long string
with many lines
and the above is empty
this is empty
hello"
So to fully clarify, I wish to remove space characters on a line that doesn't contain text, but not remove the line.
Using your example with octothorpes (yet another name for #) and replacing them with spaces in the code, we can use the String.IsNullOrWhiteSpace function to check for such lines and replace them with empty strings:
Module Module1
Sub Main()
Dim s = "This is
########a long string
with many lines
#######
and the above is empty
####this is empty
#############
#######hello"
s = s.Replace("#", " ")
Dim t = String.Join(vbCrLf, s.Split({vbCrLf}, StringSplitOptions.None).
Select(Function(a) If(String.IsNullOrWhiteSpace(a), "", a)))
Console.WriteLine(t)
Console.ReadLine()
End Sub
End Module
Outputs:
This is
a long string
with many lines
and the above is empty
this is empty
hello
Use the following code:
Dim container As String = IO.File.ReadAllText("test.txt")
container = container.Replace(vbNewLine, vbCr).Replace(vbLf, vbCr)
Do While container.Contains(vbCr & vbCr)
container = container.Replace(vbCr & vbCr, vbCr)
Loop
If container.StartsWith(vbCr) Then container = container.TrimStart(Chr(13))
container = container.Replace(vbCr, vbNewLine)
IO.File.WriteAllText("test.txt", container)
It'll trim all the empty new lines and override the file (before vs. after):
Note: If you want to remove the hashes and replace that with white spaces too, just use the following:
Dim container2 As String =
My.Computer.FileSystem.ReadAllText("test.txt").Replace("#", " ")
IO.File.WriteAllText("test.txt", container2)
Try this
Dim myString = "your multiline string here"
Dim finalString As String
For each line In myString.Split(CChar(vbNewLine))
finalstring &= line.Trim() & vbNewLine
Next
Happy Friday!
I have a loop that I output the string results to a label, but I want to reverse the order of words...
So instead of the label displaying:
Charlie
Beta
Alpha
I want it to display:
Alpha
Beta
Charlie
Code:
For Each CollectionName In CollectionNames
lblResult.Text &= vbCrLf + CStr(CollectionName.Name)
Next
This uses the string function Split and reverses the order before joining them.
Function Reverse(ByVal input As String) As String
Return String.Join(" ", input.Split(" ").Reverse())
End Function
The following function will split a string into words, reverse the words and then build a string with the reversed words.
Function ReverseWords(input As String) As String
Dim words() As String = input.Split(" "c)
Array.Reverse(words)
Return String.Join(" ", words)
End Function
Note that this assumes that the words are originally separated by spaces. If they are separated by something else, you will need to adjust the arguments to the Split method.
Your comments suggest that you may simply want the reverse the values of CollectionNames. In that case, you can simply change your loop to this:
For Each CollectionName In CollectionNames
lblResult.Text = CStr(CollectionName.Name) & vbCrLf & lblResult.Text
Next
I have inserted a option in Dorpdown as follows
<option>إختر </option>
When I select this text from server side on any event I get this value
"إختر "
Now I want to replace this white space in the string. I have tried replace method of String class. But its not working.
str = str.replace(" ","")
Plz suggest
What you should do first is decode the HTML, such that text like but also & are converted to their textual counterparts (" " and "&"). You can do this with: WebUtility.HtmlDecode. Next you can use String.Trim to remove leading and tailing spaces.
Example:
string s = "إختر ";
string r = WebUtility.HtmlDecode(s).Trim();
Or the VB.NET equivalent:
Dim s As String = "إختر "
Dim r As String = WebUtility.HtmlDecode(s).Trim()
Evidently you can try to convert to spaces yourself. But there are examples where it is not that evident and your transcoder can get confused or decode strings the wrong way. Furthermore if in the future the people at W3C change their minds about how to encode text in HTML/XML, then your program will still work.
String.Trim will remove all kinds of white-space including spaces, new lines, tabs, carriage returns, etc. If you only want to remove spaces, you can use: .Trim(' '). Then you specify only to remove the given list of characters (here only ' ').
If you want to remove leading or trailing white-spaces from a string you just need to use String.Trim, but you have to re-assign the return value to the variable since strings are immutable:
string text = "إختر ";
text = text.Trim();
Note that you can also use TrimEnd in this case.
If you want to remove only space characters(not also tabs or new-line characters which are also white-spaces) use:
text = text.Trim(' ');
If you instead want to remove all spaces from a string you could do:
text = text.Replace(" ", "");
I think maybe your code is something like this
Dim str As String = "إختر "
str.Replace(" ", "")
But actually you should
Dim str As String = "إختر "
str = str.Replace(" ", "")
I have just had a similar problem.
It turns out, that this nbsp character is Chr(160) from the ASCII table. Thus, something like this is quite meaningful, for all the cases. It works, on a selected area:
Public Sub remove_space_in_string()
Dim r_range As Range
For Each r_range In Selection
r_range = Trim(r_range)
r_range = Replace(r_range, vbTab, "")
r_range = Replace(r_range, " ", "")
r_range = Replace(r_range, Chr(160), "")
Next r_range
End Sub
The question is simple, How do I define a variable which holds double quotes. when I try to define the variable like this
Dim s as String = " " " ,
VS puts an extra quote like this
Dim s as String = """"
The extra " is used to escape the " character, so the sequence of two double-quotes ("") will show up as " when your string is displayed.
You actually have it correct with the 4 quotes, that is VBs way of escaping the quotes. So, for example:
Dim oneDoubleQuote As String = """"
Dim twoDoubleQuotes As String = """"""
MessageBox.Show("One:" & oneDoubleQuote)
MessageBox.Show("Two:" & twoDoubleQuotes)
The first message box has One:" and the second has Two:""