Created
July 23, 2021 04:23
-
-
Save in-async/41d81de4185c58b2bc49ca37c9b548f7 to your computer and use it in GitHub Desktop.
predicate による文字列分割を行う `String` 拡張メソッド。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#nullable enable | |
using System; | |
using System.Collections.Generic; | |
namespace Commons { | |
public delegate bool StringSplitPredicate(ref int index); | |
public static class StringExtensions { | |
public static IEnumerable<string> Split(this string value, StringSplitPredicate predicate) { | |
if (value is null) { throw new ArgumentNullException(nameof(value)); } | |
if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } | |
int prevIndex = 0; | |
for (int i = 0; i < value.Length; i++) { | |
int currentIndex = i; | |
if (predicate(ref i)) { | |
yield return value.Substring(prevIndex, currentIndex - prevIndex); | |
prevIndex = i; | |
} | |
} | |
yield return value.Substring(prevIndex); | |
} | |
} | |
} | |
#nullable restore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment