tags:

views:

83

answers:

5

Have an email, want to remove the first "@" symbol from it, to then make sure it doesn't have more then one in the second check. Here is currently how I'm doing it.

Dim tempEmail As String = ContactEmail
Dim count As Integer = 0
If tempEmail.IndexOf("@") <> -1 Then 'check for one
    count += 1
    tempEmail.Remove(tempEmail.IndexOf("@"), 1)
End If
If tempEmail.IndexOf("@") <> -1 Then 'check for two
    count += 1
End If

If count = 1 Then
    JustifyString(ContactEmail, 66, " ", LEFT_JUSTIFY)
Else
    ContactEmail = BLANK_EMAIL
End If

But after debugging, I have found that it never actually removes the "@" symbol from the string from tempEmail. Why?

+2  A: 
tempEmail.Remove(tempEmail.IndexOf("@"), 1)

This line creates a new string without the "@". You need to set tempEmail to be equal to the command:

tempEmail = tempEmail.Remove(tempEmail.IndexOf("@"), 1)
Stephen
+4  A: 

String is immutable. All String methods do not alter the String, but instead they create a new one and return it. Try this instead:

tempEmail = tempEmail.Remove(tempEmail.IndexOf("@"), 1)
codymanix
Oh gotcha. Is this different in Java? I remember being able to do similar things there.
Scott
Not normally, I don't think. For example, the `trim()` method returns a new String, it doesn't change the one it is called on...
Stephen
+2  A: 

Remove() returns a new string. It does not modify the original.

tempEmail = tempEmail.Remove(tempEmail.IndexOf("@"), 1)
Jon B
A: 

Strings are immutable. They don't change. To get the effect you want, change the line that reads:

tempEmail.Remove(tempEmail.IndexOf("@"), 1) 

...to:

tempEmail = tempEmail.Remove(tempEmail.IndexOf("@"), 1) 
kbrimington
+1  A: 

As others have stated, strings are immutable in .NET. The Remove method returns a new string rather than changing the original object. Therefore you need to use:

tempEmail = tempEmail.Remove(tempEmail.IndexOf("@"), 1)

One quick way to determine whether the string contains multiple "@" symbols is via LINQ, rather than using IndexOf multiple times:

Dim input = "[email protected]"
Dim count = input.Count(Function(c) c = "@"c)
Console.WriteLine(count)

Then just check If count = 1 just as you do in your original If/Else block.

Ahmad Mageed