ex-int-05-numbers/Numbers/NumberString/DigitEnumerator.cs
2025-05-10 22:58:56 +02:00

59 lines
1.4 KiB
C#

using System.Collections;
namespace Numbers.NumberString;
/// <summary>
/// Allows to enumerate only the digits in a string
/// </summary>
/// <inheritdoc cref="IEnumerator{T}"/>
public sealed class DigitEnumerator : IEnumerator<int>
{
private readonly string _text;
private int _index;
/// <summary>
/// Creates a new instance of <see cref="DigitEnumerator"/> based on the given text.
/// This will be called within <see cref="NumberString.GetEnumerator"/>.
/// </summary>
/// <param name="text">The text to iterate over (containing both letters and digits)</param>
public DigitEnumerator(string text)
{
_text = text;
_index = -1;
}
public bool MoveNext()
{
while (++_index < _text.Length)
{
if (char.IsDigit(_text[_index]))
{
return true;
}
}
return false;
}
public void Reset()
{
_index = -1;
}
public int Current
{
get
{
if (_index < 0 || _index >= _text.Length || !char.IsDigit(_text[_index]))
{
return -1;
}
return GetDigit(_text[_index]);
static int GetDigit(char c) => c - '0';
}
}
object IEnumerator.Current => Current;
public void Dispose() { }
}