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
11. Input is HTML table, Remove all tags and put data in a comma/tab separated file.
Part of this was an exercise in looking up what others have already done. using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Text.RegularExpressions;
using System.Threading;
namespace lrn2CSharp11
{
class Program
{
static void Main( string[ ] args )
{
string file = "";
string html = "";
DataSet ds = null;
StringBuilder csv = new StringBuilder( );
Console.WriteLine( "Input name of a file with an HTML table in the current directory to convert to csv." );
Console.Write( ":" );
try
{
file = Console.ReadLine( );
FileStream fs = new FileStream( file, FileMode.Open, FileAccess.Read );
StreamReader sr = new StreamReader( fs );
html = sr.ReadToEnd( );
sr.Close( );
StreamWriter sw = new StreamWriter( fs.Name + ".csv" );
ds = ConvertHTMLTablesToDataSet( html );
if ( ds != null )
{
foreach ( DataTable dtc in ds.Tables )
{
int iColCount = dtc.Columns.Count;
for ( int i = 0; i < iColCount; i++ )
{
sw.Write( dtc.Columns[ i ] );
if ( i < iColCount - 1 )
{
sw.Write( "," );
}
}
sw.WriteLine( );
foreach ( DataRow dr in dtc.Rows )
{
for ( int i = 0; i < iColCount; i++ )
{
if ( !Convert.IsDBNull( dr[ i ] ) )
{
sw.Write( dr[ i ].ToString( ) );
}
if ( i < iColCount - 1 )
{
sw.Write( "," );
}
}
sw.WriteLine( );
}
sw.WriteLine( );
}
}
sw.Close( );
fs.Close( );
}
catch
{
Console.WriteLine( "WTF?!?" );
}
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;
}
private static DataSet ConvertHTMLTablesToDataSet( string HTML )
{
DataTable dt;
DataSet ds = new DataSet( );
dt = new DataTable( );
string TableExpression = "<table[^>]*>(.*?)</table>";
string HeaderExpression = "<th[^>]*>(.*?)</th>";
string RowExpression = "<tr[^>]*>(.*?)</tr>";
string ColumnExpression = "<td[^>]*>(.*?)</td>";
bool HeadersExist = false;
int iCurrentColumn = 0;
int iCurrentRow = 0;
MatchCollection Tables = Regex.Matches(
HTML,
TableExpression,
RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase
);
foreach ( Match Table in Tables )
{
iCurrentRow = 0;
HeadersExist = false;
dt = new DataTable( );
if ( Table.Value.Contains( "<th" ) )
{
HeadersExist = true;
MatchCollection Headers = Regex.Matches(
Table.Value,
HeaderExpression,
RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase
);
foreach ( Match Header in Headers )
{
dt.Columns.Add( Header.Groups[ 1 ].ToString( ) );
}
}
else
{
int columns = Regex.Matches(
Regex.Matches(
Regex.Matches(
Table.Value,
TableExpression,
RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase
)[ 0 ].ToString( ),
RowExpression,
RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase
)[ 0 ].ToString( ),
ColumnExpression,
RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase
).Count;
for ( int iColumns = 1; iColumns <= columns; iColumns++ )
{
dt.Columns.Add( "Column " + System.Convert.ToString( iColumns ) );
}
}
MatchCollection Rows = Regex.Matches(
Table.Value,
RowExpression,
RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase
);
foreach ( Match Row in Rows )
{
if ( !( ( iCurrentRow == 0 ) & HeadersExist ) )
{
DataRow dr = dt.NewRow( );
iCurrentColumn = 0;
MatchCollection Columns = Regex.Matches(
Row.Value,
ColumnExpression,
RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase
);
foreach ( Match Column in Columns )
{
dr[ iCurrentColumn ] = Column.Groups[ 1 ].ToString( );
iCurrentColumn++;
}
dt.Rows.Add( dr );
}
iCurrentRow++;
}
ds.Tables.Add( dt );
}
return ds;
}
}
}
posted by dharh 11:42 PM May 29th, 2011
10. Create files with date and time stamp appended to the name
Note: Windows does not like ':' in file names. Also I made this extension friendly so it doesn't just add a date time stamp at the end of an html file for example and instead puts the stamp just before the '.' using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace lrn2CSharp10
{
class Program
{
static void Main( string[ ] args )
{
string fileName = "";
string timestamp = DateTime.Now.ToString( "MM-dd-yyyy_HH-mm-ss" );
Console.WriteLine( "Input name of new file in the current directory to create (it will have the current date appended to it)." );
Console.Write( ":" );
try
{
fileName = Console.ReadLine( );
if ( fileName.Contains( '.' ) )
{
string scope = fileName.Split( '.' ).Last( ).ToLower( );
fileName = fileName.Replace( "." + scope, "_" + timestamp + "." + scope );
}
else
{
fileName += "_" + timestamp;
}
FileStream fs = new FileStream( fileName, FileMode.Create );
fs.Close( );
}
catch
{
Console.WriteLine( "WTF?!?" );
}
}
}
}
posted by dharh 3:20 PM Sep 30th, 2010
9. Time and Date : Get system time and convert it in different formats 'DD-MON-YYYY', 'mm-dd-yyyy', 'dd/mm/yy' etc.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lrn2csharp9
{
class Program
{
static void Main( string[ ] args )
{
DateTime now = DateTime.Now;
Console.WriteLine( "Today's date is: " + now.ToString( "MMM dd yyyy HH:mm:ss" ) );
Console.WriteLine( "Also: " + now.ToString( "dd-MMM-yyyy" ) );
Console.WriteLine( "And: " + now.ToString( "MM-d-yyyy" ) );
Console.WriteLine( "One more thing: " + now.ToString( "d/MM/yy" ) );
}
}
}
posted by dharh 3:03 PM Sep 30th, 2010
8. Open a text file and convert it into HTML file. (File operations/Strings)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace lrn2csharp8
{
class Program
{
static void Main( string[ ] args )
{
string file = "";
string html = "<html><head><title></title></head><body>{0}</body></htm>";
string textFile = "";
Console.WriteLine( "Input name of a file in the current directory to convert into an HTML document." );
Console.Write( ":" );
try
{
file = Console.ReadLine( );
FileStream fs = new FileStream( file, FileMode.Open, FileAccess.Read );
StreamReader sr = new StreamReader( fs );
while(!sr.EndOfStream)
{
string line = sr.ReadLine( );
if ( line.Length != 0 )
textFile += "<p>" + line + "</p>";
}
sr.Close( );
StreamWriter sw = new StreamWriter( fs.Name + ".html" );
sw.Write( string.Format( html, textFile ) );
sw.Close( );
fs.Close( );
}
catch ( Exception e )
{
Console.WriteLine( "WTF?!?" );
}
}
}
}
posted by dharh 2:14 AM Jan 30th, 2010
7. Printing output in different formats (say rounding up to 5 decimal places, truncating after 4 decimal places, padding zeros to the right and left, right and left justification)(Input output operations)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace lrn2CSharp7
{
class Program
{
static void Main( string[ ] args )
{
double theNumber;
Console.WriteLine( "Input a number to be formatted" );
Console.Write( ":" );
try
{
theNumber = Convert.ToDouble( Console.ReadLine( ) );
Console.WriteLine( "Original number: {0}", theNumber );
Console.WriteLine( "Rounded up to the 5th decimal place: {0}", Math.Round( theNumber, 5 ) );
Console.WriteLine( "Truncating after the 4th decimal place: {0}", Decimal.Truncate( Convert.ToDecimal( theNumber * 10000 ) ) / 10000 );
Console.WriteLine( "Padding 7 zeroes on each side: {0}", String.Format( "{0:0000000.0000000}", theNumber ) );
Console.WriteLine( "Here is a box with 20 spaces: | |" );
Console.WriteLine( "Here is the number left justified: |{0,-20}|", theNumber );
Console.WriteLine( "Here is the number right justified: |{0,20}|", theNumber );
}
catch ( FormatException fe )
{
Console.WriteLine( "You did not enter a valid number fool." );
}
Console.WriteLine( "Press esc to exit." );
while ( !keyPressHandler( Console.ReadKey( true ) ) )
{
Thread.Sleep( 250 );
/* no op */
}
}
protected static Boolean keyPressHandler( ConsoleKeyInfo input )
{
if ( input.Key == ConsoleKey.Escape )
return true;
return false;
}
}
}
posted by dharh 9:56 PM Dec 5th, 2009
6. Scientific calculator supporting addition, subtraction, multiplication, division, square-root, square, cube, sin, cos, tan, Factorial, inverse, modulus
This is a fairly simple implementation of a console calculator. It only takes 2 number expressions ( ex: 1 + 1 ) as well as / commands for most other functions, except factorial ( n! ). Very little error checking is being done. All sorts of invalid inputs will cause this to throw exceptions. using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lrn2csharp6_console
{
class Program
{
private static String Version = "0.0";
static void Main( string[ ] args )
{
Console.WriteLine( "neSP: Calc v" + Version );
Console.WriteLine( "---------------------------------" );
Console.WriteLine( "Enter Command. ( example: /help )" );
int end = 0;
while ( end == 0 )
{
String exp = "";
Console.Write( ":" );
try
{
exp = Console.ReadLine( );
}
catch ( InvalidOperationException )
{
Console.WriteLine( "Not a valid command." );
exp = "";
}
if ( exp.Length == 0 )
{
// empty command
}
else if ( exp.ToCharArray( ).First( ) == '/' )
{
if ( exp.Split( ' ' ).ToString( )[ 0 ].Equals( "/help" ) )
{
Console.WriteLine( "You are being helped:" );
Console.WriteLine( "/help - bring up this help system." );
Console.WriteLine( "/quit or /q - quit program." );
Console.WriteLine( "/prime n - generate prime numbers from 2 to n." );
Console.WriteLine( "/factor numerator/denominator - factors fraction." );
Console.WriteLine( "/sqrt n - finds the square root of n." );
Console.WriteLine( "/cbrt n - finds the cube root of n." );
Console.WriteLine( "/sin n - finds sine of n." );
Console.WriteLine( "/cos n - finds cosine of n." );
Console.WriteLine( "/tan n - finds tangent of n." );
Console.WriteLine( "/inv numerator/denominator - finds inverse of fraction." );
Console.WriteLine( "n! - finds factorial of n." );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/quit" ) || exp.Split( ' ' )[ 0 ].Equals( "/q" ) )
{
end = 1;
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/primes" ) )
{
Console.Write( "primes:" );
prime( Convert.ToInt32( exp.Split( ' ' )[ 1 ] ) );
Console.WriteLine( );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/factor" ) )
{
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/sqrt" ) )
{
Console.WriteLine( Math.Sqrt( Convert.ToDouble( exp.Split( ' ' )[ 1 ] ) ) );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/cbrt" ) )
{
double power = 1.0 / 3.0;
Console.WriteLine( Math.Pow( Convert.ToDouble( exp.Split( ' ' )[ 1 ] ), power ) );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/sin" ) )
{
Console.WriteLine( Math.Sin( Convert.ToDouble( exp.Split( ' ' )[ 1 ] ) ) );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/cos" ) )
{
Console.WriteLine( Math.Cos( Convert.ToDouble( exp.Split( ' ' )[ 1 ] ) ) );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/tan" ) )
{
Console.WriteLine( Math.Tan( Convert.ToDouble( exp.Split( ' ' )[ 1 ] ) ) );
}
else if ( exp.Split( ' ' )[ 0 ].Equals( "/inv" ) )
{
String fraction = exp.Replace( "/inv ", "" );
double numer = Convert.ToDouble( fraction.Split( '/' )[ 0 ] );
double denom = Convert.ToDouble( fraction.Split( '/' )[ 1 ] );
Console.WriteLine( denom / numer );
}
else
{
Console.WriteLine( "Invalid command ( " + exp + " ) supplied." );
}
}
else if ( exp.Contains( '!' ) )
{
int f = Convert.ToInt32( exp.Split( '!' )[ 0 ] );
Console.WriteLine( f );
int total = 1;
for ( int i = 0; i < f; i++ )
{
total = total * ( i + 1 );
}
Console.WriteLine( total );
}
else
{
calc( exp );
}
}
}
static void calc( String expression )
{
String[ ] stack = expression.Split( ' ' );
Console.WriteLine( doCalc( Convert.ToDouble( stack[ 0 ] ), Convert.ToChar( stack[ 1 ] ), Convert.ToDouble( stack[ 2 ] ) ) );
}
static double doCalc( double left, char theOperator, double right )
{
double total = 0.0;
if ( theOperator == '+' )
{
total = add( left, right );
}
else if ( theOperator == '-' )
{
total = subtract( left, right );
}
else if ( theOperator == '*' )
{
total = multiply( left, right );
}
else if ( theOperator == '/' )
{
total = divide( left, right );
}
else if ( theOperator == '^' )
{
total = Math.Pow( left, right );
}
else if ( theOperator == '%' )
{
total = mod( Convert.ToInt32( left ), Convert.ToInt32( right ) );
}
return total;
}
static double add( double num, double num2 )
{
return ( num + num2 );
}
static double subtract( double num, double num2 )
{
return ( num - num2 );
}
static double multiply( double num, double num2 )
{
return ( num * num2 );
}
static double divide( double num, double num2 )
{
if ( num2 == 0 )
{
Console.WriteLine( "ERROR: Division by zero." );
return num;
}
else
{
return ( num / num2 );
}
}
static int mod( int num, int num2 )
{
return ( num % num2 );
}
static void prime( int num )
{
int count = 0;
for ( int _i = 2; _i < num; _i++ )
{
if ( !isPrime( _i ) )
{
if ( ( count % 10 ) == 0 ) Console.WriteLine( );
Console.Write( " {0,6}", _i );
count++;
}
}
}
static bool isPrime( int num )
{
bool notPrime = false;
for ( int k = num - 1; k > 1 && !notPrime; k-- )
{
if ( num % k == 0 ) notPrime = true;
}
return notPrime;
}
}
}
posted by dharh 8:46 PM Nov 29th, 2009
« Previous 1 2 Next »
|
AI airships america batteries blogs books browser C# c++ chatGPT computers conversation copyright covid cpp cr-48 CSharp dharh disaster DIY DRM economy energy environment FCC gaming google government history HTML humor idt internet interview japan java javascript linkjack linux lrn2program MLP moving music nature nefeedeater neThing neTodo networking news opensource philosophy podcasts poverty programming projects python reading religion science sick simple software space sparce tagging technology twitter unbirthday video wiki
|