开发者

Remove "@" from String

开发者 https://www.devze.com 2023-01-09 15:26 出处:网络
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.

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_EMA开发者_如何转开发IL
End If

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


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)


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

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


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 = "foo@bar.com"
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.


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)


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) 
0

精彩评论

暂无评论...
验证码 换一张
取 消