-1

I thought it should return the original string, like in this case, just "some string", but instead it throws a "String cannot be of zero length". Also why a string cannot be of zero length if I can have:
string str = "";

George Feng
  • 49
  • 1
  • 9
  • 4
    According to [MSDN](https://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx) it should throw a `ArgumentException`. – tkausl Mar 17 '18 at 03:45
  • @tkausl Thanks for reminding, I have just edited my problem. – George Feng Mar 17 '18 at 03:51
  • 1
    It’s not that strings in general can’t be of zero length, but that you can’t replace the empty string in a string with something. (The empty string can be found in a lot of places – in `"a"`, there’s one before and after the “a”, no? – and it’s just simpler to write what you mean.) – Ry- Mar 17 '18 at 03:51
  • It makes no sense to try to replace the empty string by something. – dcg Mar 17 '18 at 03:52
  • @dcg I just got into a situation to write something like "asd".Replace(str??" ",""); which if str is null then replaces nothing. – George Feng Mar 17 '18 at 03:55
  • @GeorgeFeng: Just write the explicit `str == null ? …` check, then. – Ry- Mar 17 '18 at 03:56

1 Answers1

3

Every string contains the empty string. If you were to try and replace the empty string with something else, Replace() would never finish because it would just keep adding the replacement string to your string an infinite number of times and never finish.

If you're trying to do a search-and-replace operation with a variable search string, just check if the search string is empty and don't perform the search if it is.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356