Split string to the right of delimiter - vb.net

I am trying to obtain the string to the right of the delimiter "|" and anything to the left can be ignored.
I tried the following, but it gives me the values to the left
Dim s As String = "John Smith | 09F2"
Console.WriteLine(s.Substring(0, s.IndexOf("|")))
Console.WriteLine(s.Split(CChar("|"))(0))
Console.ReadKey()
Result is: John Smith. I want the 09F2 value.
I also tried the following lines of code:
Dim strEmployeeInfo As String = cmbSelectEmployee.Text
Dim employeeID = Microsoft.VisualBasic.Right(strEmployeeInfo, strEmployeeInfo.IndexOf("|"))
But the result of that is Smith | 09F2. Again I only need the 09F2

When you split on the | character, the resulting array will have "John Smith " in the first position, and " 09F2" in the second position. So you need to access the second position. Since it's 0-based pass in 1 to access the second position. Next, trim the result to get rid of any additional spaces:
Dim s As String = "John Smith | 09F2"
Dim split As String() = s.Split("|"c)
Dim result As String = split(1).Trim()

Try this:
Console.WriteLine(s.Substring(s.IndexOf("|") + 1));

Suppose you have more than one "|" in your string and you want the last part after the last "|", you can use this and also it works for the above example:
Dim SArray() As String = s.Split("|"c);
//if necessary, check the length of SArray() for correctness
Console.WriteLine(SArray(SArray.Length - 1));

I'd go with this:
Dim s As String = "John Smith | 09F2"
Console.WriteLine(s.Split("|").Last().Trim())

Related

Visual Basic loop removing the last character

I have just started to learn Visual Basic and I am having trouble with a loop. What I want it to do is print out the string "ABCDEFG" into a list box then remove the last character and print it out until only "A" is left.
This is the code I am using:
Dim abc As String = "ABCDEFG"
For i = 0 To 5
abc.Substring(0, abc.Length - 1)
lstabc.Items.Add(abc)
Next i
The desired result would look like this but all i get is lines of "ABCDEFG"
ABCDEFG
ABCDEF
ABCDE
ABCD
ABC
AB
A
You're never assigning anything different to abc, so it's always adding the full string. Also, you are not specifying a different length to substring. Try this.
Dim abc As String = "ABCDEFG"
Dim abc_alt as String
For i = 0 To abc.Length - 1
abc_alt = abc.Substring(0, abc.Length - i)
lstabc.Items.Add(abc_alt)
Next i
String in c#, vb.net are non mutable. So you need to store the result in another variable and print that variable.
Dim substr As String
substr = abc.Substring(0, abc.Length - i)
lstabc.Items.Add(substr)

Getting a substring text from a string in VB.NET

Lets say I have a text Howard Johnson, 21 (USA)
I want to get the substring of the text Johnson.
I could do this with InStr and Microsoft.VisualBasic.Left Or Mid, But I always found this method rather tedious and I want to know if there is another easier method to do this.
Dim myText As String = "Howard Johnson, 21 (USA)"
Dim textIWant As String = InStr(1, myText, Chr(32))
Dim LastName As String = Mid(myText, textIWant + 1, textIWant)
'Output: Johnson
Any suggestions?
Try this code - it uses the IndexOf function of a String to locate the first instance of a character within that String.
For a surname, the example code is looking for the first space and the first comma and taking the text in between. The assumption is that the surname is always delimited that way.
For the country, the example code is looking for the first ( and the last ) and taking the text in between. The assumption is that the country is always in round brackets.
Here's the code:
Sub Main()
Dim Input As String
Dim Surname As String
Dim Country As String
Input = "Howard Johnson, 21 (USA)"
Surname = Input.Substring(Input.IndexOf(" ") + 1, Input.IndexOf(",") - Input.IndexOf(" ") - 1)
Country = Input.Substring(Input.IndexOf("(") + 1, Input.IndexOf(")") - Input.IndexOf("(") - 1)
Console.WriteLine(Surname)
Console.WriteLine(Country)
Console.ReadKey()
End Sub
It will also work for people who have spaces in their surname e.g.:
Input = "Albert del Rosario, 75 (Phillipines)"
Surname = Input.Substring(Input.IndexOf(" ") + 1, Input.IndexOf(",") - Input.IndexOf(" ") - 1)
Will output
del Rosario
Dim myText = "Howard Johnson, 21 (USA)"
Dim LastName = myText.Split(" "c, ","c)(1) ' myText.Split(" "c, ","c) gives array {"Howard", "Johnson", "", "21", "(USA)"}

Break string up

I have a string that has 2 sections broken up by a -. When I pass this value to my new page I just want the first section.
An example value would be: MS 25 - 25
I just want to show: MS 25
I am looking at IndexOf() and SubString() but I can't find how to get the start of the string and drop the end.
This might help:
http://www.homeandlearn.co.uk/net/nets7p5.html
Basically the substring method takes 2 parameters. Start position and length.
In your case, the start position is 0 and length is going to be the position found by the IndexOf method -1.
For example:
Dim s as String
Dim result as String
s = "MS 25 - 25"
result = s.SubString(0, s.IndexOf("-")-1)
You could use the Split function on the hyphen.
.Split("-")
If you want to stay away from Split, you could use SubString
yourString.Substring(0, yourString.IndexOf("-") - 1)
EDIT
The above code will fail in the instances where there is no hyphen at all or the hyphen is in the beginning of the string, also when there are no spaces surrounding the hyphen, the full leading substring will not be returned. Consider using this for safety:
Dim pos As Integer
Dim result As String
pos = yourString.IndexOf("-")
If (pos > 0) Then
result = yourString.Substring(0, pos)
ElseIf (pos = 0) Then
result = String.Empty
Else
result = yourString
End If

Substring starting at specific character count

How would you select the last part of a string starting at a specific character count.
For example I would like to get all text after the 3rd comma. but I get an error saying
"StartIndex cannot be less than zero."
Dim testString As String = "part, description, order, get this text, and this text"
Dim result As String = ""
result = testString.Substring(testString.IndexOf(",", 0, 3))
Heres my two cents:
string.Join(",", "aaa,bbb,ccc,ddd,eee".Split(',').Skip(2));
The code "testString.IndexOf(",", 0, 3)" does not find the 3rd comma. It find the first comma starting at position 0 looking at the first 3 positions (i.e. character positions 0,1,2).
If you want the part after the last comma use something like this:
Dim testString As String = "part, description, order, get this text"
Dim result As String = ""
result = testString.Substring(testString.LastIndexOf(",") + 1)
Note the +1 to move to the character after the comma. You should really also find the index first and add checks to confirm that the index is not -1 and index < testString.Length too.
Alternatives(I assume you want all the text after last comma):
Using LastIndexOf:
' You can add code to check if the LastIndexOf returns a positive number
Dim result As String = testString.SubString(testString.LastIndexOf(",")+1)
Regular Expressions:
Dim result As String = Regex.Replace(testString, "(.*,)(.*)$", "$2")
The third argument of indexOf is the number of charcters to search. You are searching for , starting at 0 for 3 characters - that is searching the string par for a comma which does not exist so the returned index is -1, hence your error. I think that you would need to use some recursion:
Dim testString As String = "part, description, order, get this text"
Dim index As Int32 = 0
For i As Int32 = 1 To 3
index = testString.IndexOf(","c, index + 1)
If index < 0 Then
' Not enough commas. Handle this.
End If
Next
Dim result As String = testString.Substring(index + 1)
The IndexOf function only finds the "First" of the specified character. The last parameter (in your case 3) specifies how many characters to examine and not the occurence.
Refer to Find Nth occurrence of a character in a string
The function specified here finds the Nth occurance of a character. Then use the substring function on the occurance returned.
Alternative , you can also use regular expression to find the nth occurance.
public static int NthIndexOf(this string target, string value, int n)
{
Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}");
if (m.Success)
{
return m.Groups[2].Captures[n - 1].Index;
}
else
{
return -1;
}
}
I think this is what you are looking for
Dim testString As String = "part, description, order, get this text"
Dim resultArray As String() = testString.Split(New Char() {","c}, 3)
Dim resultString As String = resultArray(2)

Split Last Name First Name and Middle Name in access Query

I have Full name Field that I would like to split and remove the middle name from the name.
Names are like:
Smith,James D - > Result be : Smith, James
Doe,John Snow -> Result be: Doe, John
Here is what I did but not sure what I am missing to remove the Middle name
FName: Mid([Employee] & "",InStr(1,[Employee] & " ",",")+1)
Lname: Left([Employee] & "",InStr(1,[Employee] & "",",")+(InStr(1,[Employee] & "",",")>0))
Smith,James D - > I get -> FName: James D
Doe,John Snow -> I get -> FName: John Snow
Consistency of structure is critical in string manipulation. Assuming there will always be 3 and only 3 parts to each name and 3rd part is middle name/initial and there is no space following comma, consider:
LastFirst: Left([Employee], InStrRev([Employee]," ")-1
Last: Left([Employee], InStr([Employee],",")-1)
First: Mid(Left([Employee], InstrRev([Employee]," ")-1), Instr([Employee],",")+1)
Middle: Mid([Employee], InStrRev([Employee], " ")+1)
If any of the assumptions do not hold, then build a VBA custom function.
Call that function from query or textbox. Other answers are showing excellent methods of parsing name string with VBA function.
The more variation from assumptions, the more complicated the code. Enough variation and this could become virtually impossible to automate.
The following simple function removes Middle name and returns only Last, First even when there is no Middle name or multiple Middle Names in FullName:
Public Function FixName(fullName) As String
Dim last() As String
Dim first() As String
last = Split(fullName, ",")
FixName = last(0)
first = Split(last(1), " ")
FixName = FixName & ", " & first(0)
End Function
Haven't tested but wouldn't this work for you? Within a vba public function.
'First word being first name
FName= split([employee], ",")(0)
'Second word being the last name. This will throw `indexOutOfRange` error if employee name is only one word. Use `on error resume next` to silently ignore?
LName = split(replace([employee], ",", " "))(1)
You cannot use split directly in ms access sql but that doesn't stop you to create a custom split function.
Public function FnSplit(text as variant, index as integer, optional d as string = " ") as string
If nz(len(text),0) = 0 then exit function
On error resume next
FnSplit = split(text,d)(index)
End function
And use in your sql
Select
FnSplit([employee],0) as fName,
FnSplit(replace([employee], ",", " "),1) as lName
From
Your table
Obviously these are just another way of doing the same work as previous answers