I want to replace the numeric value in drpFPortofCall.SelectedValue.ToString
.
For example, given the string AEJEA~12060
I want the result to be AEJEA
. Given the string INNSA~12430
I want the result to be INNSA
only. How can I do this?
I tried the following but wasn't able to get through.
Dim frmport As String = drpFPortofCall.SelectedValue.ToString
frmport = frmport.Replace("~", "")
CodePudding user response:
You can use regex to extract everything until the "~".
Here is an example. And a fiddle.
Dim foo = "AEJEA~12060"
Dim match = Regex.Match(foo,". ?(?=~)")
Dim x = match.Value
Console.WriteLine("x = " & x)
Edit: you will need this import:
Imports System.Text.RegularExpressions
CodePudding user response:
Easy and Simple
Using IndexOf
you will replace the rest
Dim frmport As String = drpFPortofCall.SelectedValue.ToString()
Dim value as String = frmport.Substring(0, frmport.IndexOf("~"))
CodePudding user response:
First of all, I'm pretty sure drpFPortofCall.SelectedValue
is already a string (What you have might not be a ListControl
directly, but it almost certainly inherits this property from it). That is, further calling .ToString()
from there is silly at best and wasteful at worst.
Moving on from there, it seems like you want everything up to the ~
. One option looks like this:
Dim frmport As String = drpFPortofCall.SelectedValue.Split("~"c)(0)
But that might be slower. With a little more code we could do it like this, which might be very slightly faster:
Dim endIndex As Integer = drpFPortofCall.SelectedValue.IndexOf("~"c)
Dim frmPort As String = drpFPortofCall.SelectedValue.SubString(0, endIndex)
... but you won't notice the difference unless you need to run this on 10s of thousands of inputs.
Finally, the two samples we have are strikingly similar in structure, down to the number of characters in each spot. If you can be sure that all of your data follows this format exactly, we can do even better:
Dim frmPort As String = drpFPortofCall.SelectedValue.SubString(0, 5)