Advertisement
uniblab

reading individual "words" from a buffered input

Nov 24th, 2020
926
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.48 KB | None | 0 0
  1. using System.Linq;
  2.  
  3. namespace Icod.TestRig {
  4.  
  5.     public static class Program {
  6.  
  7.         [System.STAThread]
  8.         public static System.Int32 Main( System.String[] args ) {
  9.  
  10.             var line = System.Console.In.ReadLine().TrimToNull();
  11.             while ( !System.String.IsNullOrEmpty( line ) ) {
  12.                 foreach ( var word in ReadWord( line ) ) {
  13.                     System.Console.Out.WriteLine( word );
  14.                 }
  15.                 line = System.Console.In.ReadLine().TrimToNull();
  16.             }
  17.  
  18.             System.Console.Error.WriteLine( "(Strike any key to exit.)" );
  19.             System.Console.ReadKey( true );
  20.             return 0;
  21.         }
  22.  
  23.         public static System.String TrimToNull( this System.String @string ) {
  24.             if ( System.String.IsNullOrEmpty( @string ) ) {
  25.                 return null;
  26.             }
  27.             @string = @string.Trim();
  28.             if ( System.String.IsNullOrEmpty( @string ) ) {
  29.                 return null;
  30.             }
  31.             return @string;
  32.         }
  33.  
  34.         public static System.Collections.Generic.IEnumerable<System.String> ReadWord( System.String input ) {
  35.             input ??= System.String.Empty;
  36.  
  37.             var inlen = input.Length;
  38.             System.Int32 start = 0;
  39.             System.Int32 stop;
  40.             do {
  41.                 while (  ( start < inlen ) && System.Char.IsWhiteSpace( input[ start ] ) ) {
  42.                     start++;
  43.                 }
  44.                 stop = start;
  45.                 while ( ( stop < inlen ) && !System.Char.IsWhiteSpace( input[ stop ] ) ) {
  46.                     stop++;
  47.                 }
  48.                 if ( start == stop ) {
  49.                     yield break;
  50.                 } else {
  51.                     yield return input.Substring( start, stop - start );
  52.                 }
  53.                 start = stop;
  54.             } while ( start < inlen );
  55.  
  56.             yield break;
  57.         }
  58.  
  59.     }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement