Runtime: API proposal: string.SubstringUntil/string.SubstringAfter

Created on 7 Dec 2019  路  4Comments  路  Source: dotnet/runtime

Proposal to add 4 new APIs as extensions to the string class:

```c#
public static string SubstringUntil(this string s, string sub,
StringComparison comparison = StringComparison.Ordinal);

public static string SubstringAfter(this string s, string sub,
StringComparison comparison = StringComparison.Ordinal);

public static string SubstringUntilLast(this string s, string sub,
StringComparison comparison = StringComparison.Ordinal);

public static string SubstringAfterLast(this string s, string sub,
StringComparison comparison = StringComparison.Ordinal);

These methods would work by searching for the first (or last in case with `...Last` methods) occurrence of the string `sub` in the string `s` and return the substring before that occurrence (or after).

Example usages:

```c#
var a = "name = value";

var name = a.SubstringUntil("=").Trim(); // "name"
var value = a.SubstringAfter("=").Trim(); // "value"

```c#
var a = "foo;bar;pipe";

// Get the text in the middle
var bar = a.SubstringUntilLast(";").SubstringAfter(";"); // "bar"
```

This API provides a more straightforward approach for some basic parsing needs.

Example implementation:

https://github.com/Tyrrrz/Extensions/blob/a42e1f5d729fa50fee51562e46b5b09f5dc3f31b/Tyrrrz.Extensions/StringExtensions.cs#L172-L242

api-suggestion area-System.Runtime

Most helpful comment

Before also makes it more explicit that the bound is exclusive.

All 4 comments

If this is added, I think it would be important to offer Memory and Span-based versions too.

Small nit: XSLT has functions substring-before and substring-after. It might be nicer to name it SubstringBefore instead of SubstringUntil.

Before also makes it more explicit that the bound is exclusive.

Related: https://github.com/dotnet/corefx/issues/33543 and Utf8String.TryFind. If we exposed the latter TryFind method on string and ROS<char> then writing the Substring* methods proposed here would be very straightforward.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ebickle picture ebickle  路  318Comments

jamesqo picture jamesqo  路  182Comments

morganbr picture morganbr  路  225Comments

fiigii picture fiigii  路  181Comments

galvesribeiro picture galvesribeiro  路  185Comments