skip to Main Content

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

3

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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("~"))
    
    Login or Signup to reply.
  3. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search