uniblab icon

reading individual "words" from a buffered input

uniblab | PRO | 11/24/20 11:06:45 PM UTC | 0 ⭐ | 2023 👁️ | Never ⏰ | []
C# |

1.48 KB

|

None

|

0 👍

/

0 👎

using System.Linq;
 
namespace Icod.TestRig {
 
    public static class Program {
 
        [System.STAThread]
        public static System.Int32 Main( System.String[] args ) {
 
            var line = System.Console.In.ReadLine().TrimToNull();
            while ( !System.String.IsNullOrEmpty( line ) ) {
                foreach ( var word in ReadWord( line ) ) {
                    System.Console.Out.WriteLine( word );
                }
                line = System.Console.In.ReadLine().TrimToNull();
            }
 
            System.Console.Error.WriteLine( "(Strike any key to exit.)" );
            System.Console.ReadKey( true );
            return 0;
        }
 
        public static System.String TrimToNull( this System.String @string ) {
            if ( System.String.IsNullOrEmpty( @string ) ) {
                return null;
            }
            @string = @string.Trim();
            if ( System.String.IsNullOrEmpty( @string ) ) {
                return null;
            }
            return @string;
        }
 
        public static System.Collections.Generic.IEnumerable<System.String> ReadWord( System.String input ) {
            input ??= System.String.Empty;
 
            var inlen = input.Length;
            System.Int32 start = 0;
            System.Int32 stop;
            do {
                while (  ( start < inlen ) && System.Char.IsWhiteSpace( input[ start ] ) ) {
                    start++;
                }
                stop = start;
                while ( ( stop < inlen ) && !System.Char.IsWhiteSpace( input[ stop ] ) ) {
                    stop++;
                }
                if ( start == stop ) {
                    yield break;
                } else {
                    yield return input.Substring( start, stop - start );
                }
                start = stop;
            } while ( start < inlen );
 
            yield break;
        }
 
    }
 
}

Comments