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

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"

Related

Cut String inside Quotation Mark

I have this String:
"[" & vbCrLf & " ""APPLE""" & vbCrLf & "]"
The only thing I need is APPLE.
I tried a few options with Split, Trim, Left and more, but they didn't work very well.
Thank you very much!
As the comments above have said, there's not enough information to give an answer without making assumptions, which could be wrong. I've assumed you want to extract the value between two quotation marks, regardless of what else is before or after.
If that's what you want, try this:
Dim Result As String = Nothing
Dim source As String = $"[{vbCrLf}""Apple""{vbCrLf}]"
Dim FirstQuote As Integer = source.IndexOf("""")
If FirstQuote > -1 And source.Length > FirstQuote Then
Dim SecondQuote As Integer = source.IndexOf("""", FirstQuote + 1)
If SecondQuote > FirstQuote Then
Result = source.Substring(FirstQuote + 1, SecondQuote - FirstQuote - 1)
End If
End If
If Result Is Nothing Then
'Handle Invalid Format
Else
'Process Result
End If
You would need to modify that so that you passed your source string, rather than defining it in the code. If you wanted to extract multiple words from a single string in the same format, just set FirstQuote = SecondQuote + 1, check that doesn't exceed the length of the source string and loop through again.
I am going to assume that you probably just need to get the first occurance of a string (in this case "apple") within square-brackets using split and so:
Dim AppleString As String = "This is an [Apple] or etc [...]"
console.WriteLine(AppleString.split("[")(1).split("]")(0).trim())
⚠️ This is not a solution for all purposes !!!

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, " "))

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

Add text before specific characters

str as String = " " +"thisrocks" + " "
and strArray(0) = 123456sdv :'++':
so i want to add str before the :'++':, and then
strArray(0) = 123456sdv thisrocks :'++':
Is it possible ?
What could I do to search for it ? Regex maybe ?
str and strArray will already be there from previous codes. I just want to combine it int he right place.
Using the space in between will not be helpful as the strArray(0) could also be, dsf dsv dsgvsvs svs svssd bdsb sbdfb bsbb sb s sbsfbfsbsbfs :'++': and so on.
I can't control it as they come like that from previous codes and there is no way to fix them :/
I can't generalize the question since it is not clear enough, for this occasion you can use the following code to insert a string in between these two words
Dim str As String = " " + "thisrocks" + " "
Dim strArray(10) As String
strArray(0) = "123456sdv :'++':"
strArray(0) = strArray(0).Replace(":'++':", str & ":'++':")
Output will be
"123456sdv thisrocks :'++':"
Note:
this will work as, replace :'++': with & str and add :'++': to it so :'++': will stay their for the next replacement.
You can use String.IndexOf to find where the marker :'++': is and String.Insert to insert the required data:
Dim sample As String = "123456sdv :'++':"
Dim insertData As String = " thisrocks "
Dim marker As String = ":'++':"
Dim insertPos As Integer = sample.IndexOf(marker)
If insertPos >= 0 Then
sample = sample.Insert(insertPos, insertData)
End If
Console.WriteLine(sample) ' outputs "123456sdv thisrocks :'++':"

Left split, getting blank return.

Issue, where the character I am removing does not exist I get a blank string
Aim: To look for three characters in order and only get the characters to the left of the character I am looking for. However if the character does not exist then to do nothing.
Code:
Dim vleftString As String = File.Name
vleftString = Left(vleftString, InStr(vleftString, "-"))
vleftString = Left(vleftString, InStr(vleftString, "_"))
vleftString = Left(vleftString, InStr(vleftString, " "))
As a 'fix' I have done
Dim vleftString As String = File.Name
vleftString = Replace(vleftString, "-", " ")
vleftString = Replace(vleftString, "_", " ")
vleftString = Left(vleftString, InStr(vleftString, " "))
vleftString = Trim(vleftString)
Based on Left of a character in a string in vb.net
If File.Name is say 1_2.pdf it passes "-" and then works on line removing anything before "" (though not "" though I want it to)
When it hits the line for looking for anything left of space it then makes vleftString blank.
Since i'm not familiar (and avoid) the old VB functions here a .NET approach. I assume you want to remove the parts behind the separators "-", "_" and " ", then you can use this loop:
Dim fileName = "1_2.pdf".Trim() ' Trim used to show you the method, here nonsense
Dim name = Path.GetFileNameWithoutExtension(fileName).Trim()
For Each separator In {"-", "_", " "}
Dim index = name.IndexOf(separator)
If index >= 0 Then
name = name.Substring(0, index)
End If
Next
fileName = String.Format("{0}{1}", name, Path.GetExtension(fileName))
Result: "1.pdf"