Skip to content

Instantly share code, notes, and snippets.

@in-async
Created July 23, 2021 04:23
Show Gist options
  • Save in-async/41d81de4185c58b2bc49ca37c9b548f7 to your computer and use it in GitHub Desktop.
Save in-async/41d81de4185c58b2bc49ca37c9b548f7 to your computer and use it in GitHub Desktop.
predicate による文字列分割を行う `String` 拡張メソッド。
#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