Question Using String Replace
Hello all,
I have to convert an Email address before I search a database. I have to Change the (.) Period to an (_) Underscore before I search and the string replace changes ALL the periods to underscore.
I need to replace the period in the Name and not in the .COM
This ([email protected]) needs to be ([email protected])
Using the replace method it turns into this
some_one@here_com
Is there a way to change the first occurrence only?
-NJ
Re: Question Using String Replace
Is it just the 1st occurrence of the period? What if the email address is [email protected]?
This extension method will replace all periods with underscores before the @.
vb.net Code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
email.ReplacePeriodEmailUser()
End Sub
End Class
Public Module StringExtensions
<System.Runtime.CompilerServices.Extension()>
Public Sub ReplacePeriodEmailUser(ByRef text As String)
Dim split = text.Split("@"c)
text = String.Join("@"c, split(0).Replace("."c, "_"c), split(1))
End Sub
End Module
Re: Question Using String Replace
Well regex is certainly one way, here is another:
Code:
'Some email
Dim email_string As String = "[email protected]"
'Get first instance of @
Dim at_sign As Integer = email_string.IndexOf("@")
'Loop from the beginning to the @ sign
For i As Integer = 0 To at_sign
'If that certain letter is a . then...
If email_string.Substring(i, 1) = "." Then
'Replace it with an _
email_string = email_string.Substring(0, i) & "_" & email_string.Substring(i + 1)
End If
Next
Edit - MattP beat me!
Re: Question Using String Replace
That is awesome!!!
I never knew of the text.split option.
Thanks,
-NJ
Re: Question Using String Replace
Quote:
Originally Posted by
NJDevils28
I never knew of the text.split option.
Here's the documentation: String.Split Method
Re: Question Using String Replace
You can also use string builder.
Code:
Dim s As String = "[email protected]"
Dim cpy As New System.Text.StringBuilder(s)
For x As Integer = 0 To cpy.Length - 1
If cpy(x) = "."c Then
cpy(x) = "_"c
Exit For
End If
Next
s = cpy.ToString
This only works if there is a "." before the "@".