12. Extract uppercase words from a file, extract unique words
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
namespace lrn2CSharp12
{
class Program
{
static void Main( string[ ] args )
{
string file = "";
string line = "";
string[ ] words;
List<string> upperWords = new List<string>( );
List<string> uniqueWords = new List<string>( );
Console.WriteLine( "Input name of a file to read and count words." );
Console.Write( ":" );
try
{
file = Console.ReadLine( );
FileStream fs = new FileStream( file, FileMode.Open, FileAccess.Read );
StreamReader sr = new StreamReader( fs );
while ( !sr.EndOfStream )
{
line = sr.ReadLine( );
words = null;
if ( line.Length != 0 )
words = line.Split( ' ' );
if ( words != null )
{
foreach ( string w in words )
{
if ( char.IsUpper( w[ 0 ] ) )
upperWords.Add( w );
if ( !uniqueWords.Contains( w ) )
uniqueWords.Add( w );
}
}
}
sr.Close( );
fs.Close( );
}
catch
{
Console.WriteLine( "WTF?!?" );
}
Console.WriteLine( "Upper Words:" );
foreach ( string s in upperWords )
{
Console.Write( s );
Console.WriteLine( );
}
Console.WriteLine( );
Console.WriteLine( "Unique Words:" );
foreach ( string s in uniqueWords )
{
Console.Write( s );
Console.WriteLine( );
}
Console.WriteLine( );
Console.WriteLine( "Press esc to exit." );
while ( !keyPressHandler( Console.ReadKey( true ) ) )
{
Thread.Sleep( 250 );
/* no op */
}
}
private static Boolean keyPressHandler( ConsoleKeyInfo input )
{
if ( input.Key == ConsoleKey.Escape )
return true;
return false;
}
}
}
posted by dharh 1:08 AM May 30th, 2011