I want to Split a string and then Trim the results in one single line.
So the string:
"psychology ¦ history ¦ geography"
should return the following members without trailing or leading spaces:
psychology
history
geography
I've tried:
String.Split("¦").Trim
but Trim does not work for arrays. Is there a one-line method, no matter how dirty, that does this job?
I'm sure this has been duped many times but I couldn't find the relevant solution for VB.Net. Please don't just link to a question in another language without explaining how I can convert the solution to VB.Net.
You can Split and Trim your string in one line using the LINQ's Select method.
Both assigning the string to a local variable:
Dim input As String = "psychology ¦ history ¦ geography"
Dim result1 = input.Split("¦"c).Select((Function(s) s.Trim))
Or directly using the string as source:
Dim result2 = "psychology ¦ history ¦ geography".Split("¦"c).Select((Function(s) s.Trim))
Note that the Type of result1 and result2 is now an IEnumerable(Of String), not an array:
LINQ's methods return a IEnumerable<T> if not otherwise instructed.
Also note that this syntax supposes that Option Infer is On. If you keep it Off, you need to declare the type explicitly:
Dim result As IEnumerable(Of String) = (...)
If you need a string Array as output, you need to ask:
Dim result3 As String() = input.Split("¦"c).Select((Function(s) s.Trim)).ToArray()
About the Type Characters (c) appended to the Split method parameter:
From the Visual Basic Language Reference: Char Data Type
Type Characters. Appending the literal type character C to a
single-character string literal forces it to the Char data type. Char
has no identifier type character.
If you don't have embedded spaces in the items, you can just pass the space character as a separator as well as pipe. Combine that with the remove empty entries option and multiple space separators aren't an issue. If you need to handle other whitespace characters, you can add those.
input.Split(New String() {"|", " "}, StringSplitOptions.RemoveEmptyEntries)
Related
I am working on a vb.net application.
My code is the following:
txtTotalPrevious.Text = Val(txtTotalPrevious.Text) + Val(txtoldtotal.text)
my values are:
txtTotalPrevious.Text=187.0000
txtoldtotal=3
I get the result
result =190
but my expected result is:
result=190.0000
What is the issue in my logic?
You can use String.Format if you want to output string be like you want:
Dim str1 As String = "187.0000"
Dim str2 As String = "3"
Dim resultString As String = String.Format("{0:0.0000}", Val(str1) + Val(str2))
' And the result will be 190.0000
And if you want the double result:
Dim resultDouble as Double= Val(str1) + Val(str2)
' And the result will be Double 190
EDIT
Based on varocarbas comments you should consider some notes:
Avoid using Val method
The Val function stops reading the string at the first character it
cannot recognize as part of a number. Symbols and characters that are
often considered parts of numeric values, such as dollar signs and
commas, are not recognized. However, the function recognizes the radix
prefixes &O (for octal) and &H (for hexadecimal). Blanks, tabs, and
linefeed characters are stripped from the argument.
The following call
returns the value 1615198.
Val(" 1615 198th Street N.E.")
The Val function recognizes only the period (.) as a valid decimal
separator. When different decimal separators are used, as in
international applications, use CDbl or CInt instead to convert a
string to a number. To convert the string representation of a number
in a particular culture to a numeric value, use the numeric type's
Parse(String, IFormatProvider) method. For example, use Double.Parse
when converting a string to a Double.
As a VB.Net Programmer use & instead of + for string concatenation
When you use the + operator, you might not be able to determine
whether addition or string concatenation will occur. Use the &
operator for concatenation to eliminate ambiguity and to provide
self-documenting code.
I am having difficulties trying to figure out the syntax. I have a line of binary in a variable and i want to know how to to split that string every 7th character so i can put it in an ascii table to find its equivalent.
Based on your scenario, you can also do a substring to satisfy your requirement.
Dim theString As String = "w3rs0fd90as90f9sda0faf"
Dim FirstSevenCharacters as String= theString.Substring(0, 7)
Dim CharactersAfterTheFirstSeven as String= theString.Substring(7, theString.Length - 7)
Dim text as string = "Visual Basic"
output: "Basic"
I need to read a string and print it but not starting at the very first index. The text may vary so I want to know if there is a way to read it.
You can use the IndexOf method to find the first space, then the SubString method to get the part of the string after the space:
Dim idx As Integer = text.IndexOf(" "C);
Dim output As String = text.SubString(idx + 1);
(This even works if there would be no space at all in the string. Then idx will be -1 (the value meaning "not found"), so idx + 1 will be zero and output will be the whole string.)
My application generates CSV file from some objects. These CSV files are used in many countries so I must use correct separator.
To seperate values (cells) in a file I use separator:
Dim separator As String = My.Computer.Info.InstalledUICulture.TextInfo.ListSeparator
This should be OK. But one column contains decimal numbers so I want to be sure that I use correct decimal separator (must be different than list separator).
I am converting decimal value to a string like this:
Dim intValue as Integer = 123456
Dim strValue as String = (intValue / 100).ToString()
In my country a list separator is a semicolon and decimal separator is a comma. In this combination it is OK. But I found out that in some country where the list separator is a comma, decimal separator is comma as well. And this is a problem. How I have to convert a decimal number to string if I want to use correct local decimal separator? Thanks!
How I have to convert a decimal number to string if I want to use
correct local decimal separator?
By default the current culture's separator is used anyway. But you can use the overload of Decimal.ToString that takes a CultureInfo:
Dim localizedNumber = (intValue / 100).ToString( CultureInfo.CurrentCulture )
If you want to use a different culture:
Dim usCulture = new System.Globalization.CultureInfo("en-US")
localizedNumber = (intValue / 100).ToString( usCulture )
If you want to know the decimal separator of a given culture:
Dim separator As String = usCulture.NumberFormat.NumberDecimalSeparator
Edit So your customers don't want to use tab as separator since they have to specify the delimiter manually. You could either generate a real excel-file, for example by using EPPlus which doesn't even need an excel-license or you need to provide another solution.
I have checked it, there are 13 cultures where the decimal-separator is the same as the list-separator (used by excel):
Dim conflictCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures).
Where(Function(c) c.NumberFormat.NumberDecimalSeparator = c.TextInfo.ListSeparator)
So you have to check it manually and then provide a different list-separator. If decimal/list-separator is comma you can use semicolon as list-separator and vice-versa:
Dim argentinaCulture = New CultureInfo("es-AR") ' uses same separator for both
Dim decimalSeparator = argentinaCulture.NumberFormat.NumberDecimalSeparator ' comma
Dim listSeparator = argentinaCulture.TextInfo.ListSeparator 'comma
If decimalSeparator = listSeparator Then
listSeparator = If(listSeparator = ",", ";", ",")
End If
I am trying to split a string with multiple characters. The string might sometimes contain a - or a /. What I have achieved is the hyphen but I am not able to search for the slash. Any thoughts on how to split the string based on both characters at once ? Once I split after - I add the value after the - to the result list as a separate index and I would like to accomplish the same for '/'.
So For example the Split string has Jet-blue, the below code will add Jet in the result list with index(0) and blue with index(1). In addition to splitting with '-' I would also like to split with '/'. Any suggestions ?
Code:
Dim result As New List(Of String)()
For Each str_get As String In Split
Dim splitStr = str_get.Split("-")
For Each str_split As String In splitStr
result.Add(str_split) ' Enter into result list
' result.TrimExcess()
Next
result.Remove("")
Next
You can either use this or this overload of the Split method.
The first one takes an array of Char:
"Hello World".Split({"e"c, "o"c}) ' Notice the c!
The second one takes an array of String and StringSplitOptions:
"Hello World".Split({"el", "o"}, StringSplitOptions.None)