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

Commit db2a9b6

Browse files
committed
Add GetLeftPart and GetRightPart string ext methods
1 parent f233096 commit db2a9b6

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/ServiceStack.Text/StringExtensions.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,42 @@ private static byte[] FastToUtf8Bytes(string strVal)
335335
return bytes;
336336
}
337337

338+
public static string GetLeftPart(this string strVal, char needle)
339+
{
340+
if (strVal == null) return null;
341+
var pos = strVal.IndexOf(needle);
342+
return pos == -1
343+
? strVal
344+
: strVal.Substring(0, pos);
345+
}
346+
347+
public static string GetLeftPart(this string strVal, string needle)
348+
{
349+
if (strVal == null) return null;
350+
var pos = strVal.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
351+
return pos == -1
352+
? strVal
353+
: strVal.Substring(0, pos);
354+
}
355+
356+
public static string GetRightPart(this string strVal, char needle)
357+
{
358+
if (strVal == null) return null;
359+
var pos = strVal.IndexOf(needle);
360+
return pos == -1
361+
? strVal
362+
: strVal.Substring(pos + 1);
363+
}
364+
365+
public static string GetRightPart(this string strVal, string needle)
366+
{
367+
if (strVal == null) return null;
368+
var pos = strVal.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
369+
return pos == -1
370+
? strVal
371+
: strVal.Substring(pos + needle.Length);
372+
}
373+
338374
public static string[] SplitOnFirst(this string strVal, char needle)
339375
{
340376
if (strVal == null) return TypeConstants.EmptyStringArray;

tests/ServiceStack.Text.Tests/StringExtensionsTests.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,14 @@ public void Can_SplitOnFirst_char_needle()
1616
Assert.That(parts[1], Is.EqualTo("pass@w:rd"));
1717
}
1818

19+
[Test]
20+
public void Can_GetLeftPart_and_GetLeftPart_char_needle()
21+
{
22+
var str = "user:pass@w:rd";
23+
Assert.That(str.GetLeftPart(':'), Is.EqualTo("user"));
24+
Assert.That(str.GetRightPart(':'), Is.EqualTo("pass@w:rd"));
25+
}
26+
1927
[Test]
2028
public void Can_SplitOnFirst_string_needle()
2129
{
@@ -24,6 +32,14 @@ public void Can_SplitOnFirst_string_needle()
2432
Assert.That(parts[1], Is.EqualTo("pass@w:rd"));
2533
}
2634

35+
[Test]
36+
public void Can_GetLeftPart_and_GetLeftPart_string_needle()
37+
{
38+
var str = "user::pass@w:rd";
39+
Assert.That(str.GetLeftPart("::"), Is.EqualTo("user"));
40+
Assert.That(str.GetRightPart("::"), Is.EqualTo("pass@w:rd"));
41+
}
42+
2743
[Test]
2844
public void Can_SplitOnLast_char_needle()
2945
{

0 commit comments

Comments
 (0)