Why Does Replace Return Nothing on Empty String
Asked Answered
R

3

7
Replace("",vbLf, "")

Go figure.

It should return ""

No. It returns nothing.

Just put the code in vb.net

I think it should return "". Replace all occurance of vbLF with "". Because the original string is "" then it simply replace nothing and we got back ""

\No. We got back nothing.

Riel answered 28/2, 2012 at 2:49 Comment(1)
Could you re-write your question using sentences with verbs and a question mark to indicate what question you'd like answered? This is unclear.Sarawak
S
3

You are using Visual Basic string functions, not .Net. The Visual Basic runtime usually evaluates Nothing as an empty string ("").

Stronski answered 28/2, 2012 at 3:8 Comment(2)
hmm... let me check string.replace insteadRiel
"evaluates" should be "equates"Bilabial
L
1

I second the original post, VB.net should not return NOTHING with its REPLACE function. However, it does if your replace happens to return Nothing if the expression is an empty string.

Looby answered 27/11, 2013 at 7:12 Comment(0)
V
0

To elaborate on this for anyone winding up here, when you just call "Replace" you're getting Microsoft.VisualBasic.Replace, not the String.Replace you're expecting.

Microsoft.VisualBasic.Replace: https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic?view=netframework-4.7.2

String.Replace: https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=netframework-4.7.2

If you want to return an empty string you need to call the .Replace method of a String:

dim myString as String = ""
myString.Replace("a", "b")

This of course finds no match, but the behavior is instead to return and empty string now instead of Nothing when the input expression is an empty String.

Vibrate answered 3/11, 2022 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.