Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 8b6a91e

Browse files
committed
Replace ReplaceAll with built-in string.Replace()
1 parent 7e624b9 commit 8b6a91e

File tree

2 files changed

+15
-14
lines changed

2 files changed

+15
-14
lines changed

src/ServiceStack.Text/StringExtensions.cs

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -922,20 +922,9 @@ public static string ReplaceFirst(this string haystack, string needle, string re
922922
return haystack.Substring(0, pos) + replacement + haystack.Substring(pos + needle.Length);
923923
}
924924

925-
public static string ReplaceAll(this string haystack, string needle, string replacement)
926-
{
927-
int pos;
928-
// Avoid a possible infinite loop
929-
if (needle == replacement)
930-
return haystack;
931-
while ((pos = haystack.IndexOf(needle, StringComparison.Ordinal)) >= 0)
932-
{
933-
haystack = haystack.Substring(0, pos)
934-
+ replacement
935-
+ haystack.Substring(pos + needle.Length);
936-
}
937-
return haystack;
938-
}
925+
[Obsolete("Use built-in string.Replace()")]
926+
public static string ReplaceAll(this string haystack, string needle, string replacement) =>
927+
haystack.Replace(needle, replacement);
939928

940929
public static bool ContainsAny(this string text, params string[] testMatches)
941930
{

tests/ServiceStack.Text.Tests/StringExtensionsTests.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.IO;
33
using System.Linq;
4+
using System.Threading.Tasks;
45
using NUnit.Framework;
56

67
namespace ServiceStack.Text.Tests
@@ -362,6 +363,17 @@ public void Does_ReplaceAll_from_Start()
362363
Assert.That("/images".ReplaceAll("/",""), Is.EqualTo("images"));
363364
}
364365

366+
[Test]
367+
public void Does_ReplaceAll_Avoid_Infinite_Loops()
368+
{
369+
var input = "image";
370+
var output = input;
371+
372+
output = input.ReplaceAll("image", "images");
373+
374+
Assert.That(output, Is.EqualTo("images"));
375+
}
376+
365377
[TestCase("", ExpectedResult = "/")]
366378
[TestCase("/", ExpectedResult = "/")]
367379
[TestCase("?p1=asdf", ExpectedResult = "/?p1=asdf")]

0 commit comments

Comments
 (0)