How to replace ~ with " from string in VB.net - vb.net

Am using Replace("~", chr(34)) but output am getting is this
Output:
{""Code"":""101"",""Description"":""demo - account""}
This is existing string:
{~Code~:~101~,~Description~:~demo - account~}
Desired output i want is this: {"Code":"101","Description":"demo - account"}

You can test the following code:
Sub ReplaceInString()
Dim original As String = "{~Code~:~101~,~Description~:~demo - account~}"
Dim replaced As String = original.Replace("~", """")
Console.WriteLine("Original string is: " & original)
Console.WriteLine("Result string is: " & replaced)
End Sub
If you want to specify the " char, you need to write it twice between other double quotes, """".
From my test, I get the result you expect.

Related

Getting value in the middle of a string

I am try to get value in the middle of a string
My string is
"arely browning,68097,19
I know I can use a substring and pick a specific place but I want it to work for any line that is format like this
If the format of the string remains the same, then this will do it:
Dim MyString As String = "arely browning,68097,19"
Dim StringPart As String = Mid(MyString, InStr(MyString, " "), InStr(MyString, ",") - InStr(MyString, " "))

Parsing numbers containing commas or periods

I have three values which need to be sorted from highest to lowest value. I use the following code which works like a charm until I want to use periods "." and commas ",". If I type "1,3" it displays as I like, but if I type "1.3" it changes to 13. My end users need to be able to use both commas and periods.
How can I fix this?
Dim IntArr(2) As Decimal
IntArr(0) = TextBox1.Text
IntArr(1) = TextBox2.Text
IntArr(2) = TextBox3.Text
Array.Sort(IntArr)
Dim highestNum As Decimal
Dim Midelnum As Decimal
Dim lowestNum As Decimal
lowestNum = IntArr(0)
Midelnum = IntArr(1)
highestNum = IntArr(2)
MsgBox("Highest " & highestNum)
MsgBox("lowest " & lowestNum)
MsgBox("middel " & Midelnum)
The problem is that it's based on culture. I say this because if I enter numbers as you described, I get the opposite effect ("1,3" -> "13", etc).
Here's a quick way to change the values to match the current culture.
At the top of your class, put this:
Imports System.Globalization
Then, you can do this:
Dim IntArr(2) As Decimal
Dim nfi As NumberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
Dim sep1 As String = nfi.NumberDecimalSeparator
Dim sep2 As String = If(sep1.Equals("."), ",", ".")
Dim useComma As Boolean = (TextBox1.Text.Contains(",") Or TextBox2.Text.Contains(",") Or TextBox3.Text.Contains(","))
'Replace the separator to match the current culture for parsing
Decimal.TryParse(TextBox1.Text.Replace(sep2, sep1), IntArr(0))
Decimal.TryParse(TextBox2.Text.Replace(sep2, sep1), IntArr(1))
Decimal.TryParse(TextBox3.Text.Replace(sep2, sep1), IntArr(2))
Array.Sort(IntArr)
sep1 = If(useComma, ",", ".")
sep2 = If(useComma, ".", ",")
'Reformat the results to match the user's input
Dim lowestNum As String = IntArr(0).ToString().Replace(sep2, sep1)
Dim middleNum As String = IntArr(1).ToString().Replace(sep2, sep1)
Dim highestNum As String = IntArr(2).ToString().Replace(sep2, sep1)
Dim msg As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
msg = String.Format(msg, highestNum, lowestNum, middleNum)
MessageBox.Show(msg)
Also, since you are using .NET, you may want to skip the VB6 way of doing things. Refer to my example to see what I've used.
You could use the hack of altering the string before saving it:
TextBox.Text.Replace(".",",")
But if you want to show the original input you could have a variable to detect the entered character:
Dim isDot As Boolean = False
Dim number As String = TextBox.Text
If number.Contains(".") Then
isDot = True
End If
And in the end replace it just for purposes of displaying
If isDot Then
number.Replace(",",".")
End If
The accepted answer uses too much unnecessary string manipulation. You can use the CultureInfo object to get what you need:
Sub Main
Dim DecArr(2) As Decimal
'Select the input culture (German in this case)
Dim inputCulture As CultureInfo = CultureInfo.GetCultureInfo("de-DE")
Dim text1 As String = "1,2"
Dim text2 As String = "5,8"
Dim text3 As String = "4,567"
'Use the input culture to parse the strings.
'Side Note: It is best practice to check the return value from TryParse
' to make sure the parsing actually succeeded.
Decimal.TryParse(text1, NumberStyles.Number, inputCulture, DecArr(0))
Decimal.TryParse(text2, NumberStyles.Number, inputCulture, DecArr(1))
Decimal.TryParse(text3, NumberStyles.Number, inputCulture, DecArr(2))
Array.Sort(DecArr)
Dim format As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
'Select the output culture (US english in this case)
Dim ouputCulture As CultureInfo = CultureInfo.GetCultureInfo("en-US")
Dim msg As String = String.Format(ouputCulture, format, DecArr(2), DecArr(1), DecArr(0))
Console.WriteLine(msg)
End Sub
This code outputs:
Highest: 5.8
Lowest: 4.567
Middle: 1.2

VBA function to convert name format

I want to take a name in First Last format and change it to Last, First. I know I could to this with a formula but I want to be complicated.
Please let me know if you see any red flags in my code, or suggestions for improvements.
Function LastFirst(Name_FL As String)
'This only works if there is a single space in the cell - Will Error If Spaces <> 1
Length = Len(Name_FL) 'Establishes Length of String
Spaces = Length - Len(Application.WorksheetFunction.Substitute(Name_FL, " ", "")) 'Number of spaces
If Spaces <> 1 Then
LastFirst = "#SPACES!#" 'Error Message
Else
SpaceLocation = Application.WorksheetFunction.Find(" ", Name_FL, 1) 'Location of space
Last = Right(Name_FL, Length - SpaceLocation) 'Establishes Last Name String
First = Left(Name_FL, SpaceLocation) 'Establishes First Name String
LastFirst = Application.WorksheetFunction.Proper(Last & ", " & First) 'Puts it together
End If
End Function 'Ta-da
You could simplify it to:
Function LastFirst(Name_FL As String) As String
If (Len(Name_FL) - Len(Replace(Name_FL, " ", ""))) > 1 Then
LastFirst = "#SPACES#"
Else
LastFirst = StrConv(Split(Name_FL, " ")(1) & ", " & Split(Name_FL, " ")(0), vbProperCase)
End If
End Function
The logic here is:
If there is more than 1 space, return the error string #SPACES#
If there is 1 space, the split the string using " " as a delimiter.
Use the second index of the Split array, add ", " and use the first index of the split array.
Use StrConv() to convert it all to proper case.
You might also want to add another check for no spaces:
If InStr(Name_FL, " ") > 0 Then
'// There is a space in the string
Else
'// There is no space in the string
End If
Which can also be tested for by slightly changing the logic of the above example:
Function LastFirst(Name_FL As String) As String
If (Len(Name_FL) - Len(Replace(Name_FL, " ", ""))) = 1 Then
LastFirst = StrConv(Split(Name_FL, " ")(1) & ", " & Split(Name_FL, " ")(0), vbProperCase)
Else
LastFirst = "#SPACES#"
End If
End Function
Further elaboration on functions:
You can see I've used some VBA functions here in place of your WorksheetFunction methods.
Len() returns the Length of a string.
Replace() does what it says on the tin - replaces a given string with another.
StrConv() Converts a String to a respective case (e.g. vbProperCase).
Split() Creates a zero-based single dimension array from a string, by Splitting it on a given delimiter.
Finally - Don't forget to specify a return value in your function header:
Function LastFirst(Name_FL As String)As String<~~ return type

VB.NET: Convert string containing "Lastname, Firstname" to "Firstname Lastname"

I'm trying to convert a string that contains someones name as "Last, First" to "First Last".
This is how I am doing it now:
name = name.Trim
name = name.Substring(name.IndexOf(",") + 1, name.Length) & " " & name.Substring(0, name.IndexOf(",") - 1)
When I do this I get the following error:
ArgumentOutOfRangeException was unhandled
Index and length must refer to a location within the string
Parameter name: length
Can someone explain why I am getting this error and how I should be doing this?
You are getting error on this:
name.Substring(name.IndexOf(",") + 1, name.Length)
name.Length should have subtracted with the length of the string before the comma.
The best way for that is to split the string.
Dim oFullname as string = "Last, First"
Dim oStr() as string = oFullname.split(","c)
oFullname = oStr(1).trim & " " & oStr(0).trim
MsgBox (oFullname)
The second parameter for String.Substring is the length of the substring, not the end position. For this reason, you're always going to go out of bounds if you do str.Substring(n, str.Length) with n > 0 (which would be the whole point of a substring).
You need to subtract name.IndexOf(",") + 1 from name.Length in your first substring. Or just split the string, as the others have suggested.
simply ,you only need to split the string
Dim originalName As String = "Last,First"
Dim parts = name.Split(","C)
Dim name As String = parts(1) & " " & parts(0)
If you're using the Unix command line--like the terminal on a Mac--you can do it like this:
Let's say that you have a file containing your last-comma-space-first type names like this:
Last1, First1
Last2, First2
Last3, First3
OK, now let's save it as last_comma_space_first.txt. At this point you can use this command I came up with for your particular problem:
sed -E 's/([A-Za-z0-9]+), ([A-Za-z0-9]+)/\2 \1/g' last_comma_space_first.txt > first_space_last.txt
--->>> Scroll --->>>
You're done! Now, go check that first_space_last.txt file! ^_^ You should get the following:
First1 Last1
First2 Last2
First3 Last3
Tell your friends... Or don't...
This would work keeping to the posters format.
Name = "Doe,John"
Name = Replace(Name.Substring(Name.IndexOf(","), Name.Length - Name.IndexOf(",")) & " " & Name.Substring(0, Name.IndexOf(",")), ",", "")
Result Name = "John Doe"

What's the differences between "{0}" and "&" in VB.NET?

Please be easy on me guys as I'm still learning.
The following code:
Imports System.Console
Module Module1
Sub Main()
Dim num As Integer
Dim name As String
num = 1
name = "John"
WriteLine("Hello, {0}", num)
WriteLine("Hello, {0}", name)
WriteLine("Hello, {0}", 1)
WriteLine("Hello, {0}", "John")
WriteLine("5 + 5 = {0}", 5 + 5)
WriteLine()
End Sub
End Module
has the same output as this code:
Imports System.Console
Module Module1
Sub Main()
Dim num As Integer
Dim name As String
num = 1
name = "John"
WriteLine("Hello, " & num)
WriteLine("Hello, " & name)
WriteLine("Hello, " & 1)
WriteLine("Hello, " & "John")
WriteLine("5 + 5 = " & 5 + 5)
WriteLine()
End Sub
End Module
Both output:
Hello, 1
Hello, John
Hello, 1
Hello, John
5 + 5 = 10
I looked everywhere and couldn't find the answer.
When to use "{0}, {1}, ... etc"? and when to use "&"?
Which is better? And why?
With {0} you're specifying a format placeholder, whereas with & you're just concatenating the string.
Using format placeholders
Dim name As String = String.Format("{0} {1}", "James", "Johnson")
Using string concatenation
Dim name As String = "James" & " " & "Johnson"
What you're seeing here are two very different expressions that just so happen to evaluate to the same output.
The & operator in VB.Net is the string concatenation operator. It essentially works by converting both the left and right side of the expression to a String and them adding them together. This means all the below operations are roughly equivalent
"Hello " & num
"Hello " & num.ToString()
"Hello " & CStr(num)
The {0} is a feature of the .Net APIs. It represents a position within a string which will later be replaced with a value. The {0} refers to the first value passed to the function, {1} the second and so on. This means that all the below operations are roughly equivalent
Console.WriteLine("Hello {0}!", num)
Console.WriteLine("Hello " & num & "!")
The reason you see the same output is because putting {0} at the end of the string is almost exactly the same as a string concatenation of the 2 values.
Using {N} is called Composite Formatting. One advantage, besides readability, is the fact that you can easily set alignment and format properties. Example from the MSDN link:
Dim MyInt As Integer = 100
Console.WriteLine("{0:C}", MyInt)
' The example displays the following output
' if en-US is the current culture:
' $100.00
{0} is a placeholder that is used in conjunction with String.Format in order to have a more readable and performant string substitutions. Several method calls, including WriteLine, have implicit calls to String.Format.
The problem with using concatenation is that each concat operation will create a new string, which consumes memory.
If you are performing a lot of substitutions, then the best performance will be to use System.Text.StringBuilder instead.