Author Topic: Read file, write file  (Read 11146 times)

0 Members and 1 Guest are viewing this topic.

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
Read file, write file
« on: February 06, 2008, 08:19:50 PM »
ok, I'm sure there is a MUCH better way to do this, but I'm trying to bang this out real fast.  Im opening a file, and parsing character by character and counting how many "A's", "B's", etc.  Eventually I will write this out to a file, but I'm interested if anyone has a better way to parse this information.
Code: [Select]
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Signage
{
    class Program
    {
        public static void Main(string[] args)
        {
            int intA = 0;
            int intB = 0;
            int intC = 0;
            int intD = 0;
            int intE = 0;
            int intF = 0;
            int intG = 0;
            int intH = 0;
            int iniI = 0;
            int intJ = 0;
            int intK = 0;
            int intL = 0;
            int intM = 0;
            int intN = 0;
            int intO = 0;
            int intP = 0;
            int intQ = 0;
            int intR = 0;
            int intS = 0;
            int intT = 0;
            int intu = 0;
            int intV = 0;
            int intW = 0;
            int intX = 0;
            int intY = 0;
            int intZ = 0;
            int int1 = 0;
            int int2 = 0;
            int int3 = 0;
            int int4 = 0;
            int int5 = 0;
            int int6 = 0;
            int int7 = 0;
            int int8 = 0;
            int int9 = 0;
            int int0 = 0;

            using (StreamReader sr = new StreamReader("c:/TestFile.txt"))
            {

                string currentChar;
                while ((currentChar = sr.Read().ToString()) != "-1")
                {
                    switch (currentChar)
                    {
                        case "65":
                            intA++;
                            break;
                        case "66":
                            intB++;
                            break;
                        case "67":
                            intC++;
                            break;
                        case "68":
                            intD++;
                            break;
                        case "69":
                            intE++;
                            break;
                        case "70":
                            intF++;
                            break;
                        case "71":
                            intG++;
                            break;
                        case "72":
                            intH++;
                            break;
                        case "73":
                            intI++;
                            break;
                        case "74":
                            intJ++;
                            break;
                        case "75":
                            intK++;
                            break;
                        case "76":
                            intL++;
                            break;
                        case "77":
                            intM++;
                            break;
                        case "78":
                            intN++;
                            break;
                        case "79":
                            intO++;
                            break;
                        case "80":
                            intP++;
                            break;
                        case "81":
                            intQ++;
                            break;
                        case "82":
                            intR++;
                            break;
                        case 83:
                        case 84:
                        case 85:
                        case 86:
                        case 87:
                        case 88:
                        case 89:
                        case 90:
                        case 91:
                        case 92:
                        case 93:
                        case 94:
                        case 95:
                        case 96:
                        case 97:
                        case 98:
                        case 99:
                        case 100:

                        default:
                            break;
                    }
                }

            }
            Console.WriteLine("A=" + intA.ToString());
            Console.WriteLine("B=" + intB.ToString());
        }
    }
}
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
Re: Read file, write file
« Reply #1 on: February 06, 2008, 08:20:52 PM »
As you can see from the code, I quit writing at about 82, looking to you guys for pointers.
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

MickD

  • King Gator
  • Posts: 3619
  • (x-in)->[process]->(y-out) ... simples!
Re: Read file, write file
« Reply #2 on: February 06, 2008, 08:34:40 PM »
Perhaps you can use a map/dictionary (yes I like those :) ), create the 'keys' with the int values using a loop and store the 'A++' in the 'value' of the key.
As you read in the keys, add one to the value in a loop, something like (pseudo code) -

// creating the dictionary/map
Dict dict = new Dict();
// create the records:
For (i=0; i<36; i++) //amount of vals
    dict.addRecord(key = 65+i.asString() , value = 0);
end

// reading and storing:
while(not end of file)
 read in a char
    dict.getAt(asAsciiNum(char)) += 1;
end while
   
hth.

PS. I'd write an example for you David but it would take me longer to set up my c# ide and study the api than it would to code it :laugh:
« Last Edit: February 06, 2008, 08:45:31 PM by MickD »
"Short cuts make long delays,' argued Pippin.”
J.R.R. Tolkien

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
Re: Read file, write file
« Reply #3 on: February 06, 2008, 08:55:54 PM »
OK, most of that went over my head, but I get the gist. :-)  I will look up Dict's tomorrow at work.
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
Re: Read file, write file
« Reply #4 on: February 06, 2008, 08:56:24 PM »
Other than that, do you think Im on track for parsing the file?
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

MickD

  • King Gator
  • Posts: 3619
  • (x-in)->[process]->(y-out) ... simples!
Re: Read file, write file
« Reply #5 on: February 06, 2008, 09:02:47 PM »
I think the logic is there, a dictionary/map is just like a db, it has a key (like primary key if you like) which is the link to the stored data. In each loop you give the dictionary the key and it gives you access to the data.
To create the dict just use a loop and create a record for each char. The best part is if the key doesn't exist (say it's a space or comma etc.) you can just 'continue' the loop.

As far as the file read/write goes I haven't looked at C# for quite a while now so I'm no real help there I'm afraid.
"Short cuts make long delays,' argued Pippin.”
J.R.R. Tolkien

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Read file, write file
« Reply #6 on: February 06, 2008, 09:35:23 PM »

David, sorry, I'm just flying past ..

perhaps Have a look an using LINQ ...

http://msdn2.microsoft.com/en-us/library/bb397940.aspx#Mtps_DropDownFilterText

OR regex may do the trick.
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

MickD

  • King Gator
  • Posts: 3619
  • (x-in)->[process]->(y-out) ... simples!
Re: Read file, write file
« Reply #7 on: February 06, 2008, 10:03:23 PM »
I just remembered too, a hashtable may be easier and faster(??).
Just another option.
"Short cuts make long delays,' argued Pippin.”
J.R.R. Tolkien

SomeCallMeDave

  • Guest
Re: Read file, write file
« Reply #8 on: February 06, 2008, 10:04:09 PM »
Breaking codes?

You could use the Enumerator of a String to read each character.

I'm sure this isn't great C# coding, but it seems to work

Code: [Select]
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace CharCount
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] counts = new int[91];
            using (StreamReader sr = new StreamReader("c:/testfile.txt"))
            {
                String fullFile = sr.ReadToEnd();
                String upper = fullFile.ToUpper();

                IEnumerator chars = upper.GetEnumerator();
                while (chars.MoveNext())
                {
                    char current = (char)chars.Current;
                    int currInt = Convert.ToInt16(current);
                    if (currInt >= 48 & currInt <= 90 )
                    {
                        counts[currInt]++;
                    }
                }
            }

            for (int i = 48; i < 58; i++)
            {
                Console.WriteLine("\nNumber of {0}'s is {1}", Convert.ToChar(i), counts[i]);
            }
            for (int i = 65; i < 91; i++)
            {
                Console.WriteLine("\nNumber of {0}'s is {1}", Convert.ToChar(i), counts[i]);
            }

            Console.WriteLine("\nHit enter to continue");
            Console.ReadLine();
        }
    }
}




MickD

  • King Gator
  • Posts: 3619
  • (x-in)->[process]->(y-out) ... simples!
Re: Read file, write file
« Reply #9 on: February 06, 2008, 10:10:03 PM »
Nice one David! Simple too :)
"Short cuts make long delays,' argued Pippin.”
J.R.R. Tolkien

SomeCallMeDave

  • Guest
Re: Read file, write file
« Reply #10 on: February 06, 2008, 10:13:00 PM »
Thanks.  Simple is about all I can do in C# :-D

It can be expanded too,  to count other characters by playing with the array index and the test values in the for loops.

MickD

  • King Gator
  • Posts: 3619
  • (x-in)->[process]->(y-out) ... simples!
Re: Read file, write file
« Reply #11 on: February 06, 2008, 10:21:05 PM »
Thanks.  Simple is about all I can do in C# :-D

It can be expanded too,  to count other characters by playing with the array index and the test values in the for loops.

Yep, with a little bit more math you could also reduce the size of the array, whether it's worth it or not though ...
"Short cuts make long delays,' argued Pippin.”
J.R.R. Tolkien

SomeCallMeDave

  • Guest
Re: Read file, write file
« Reply #12 on: February 07, 2008, 08:50:29 AM »
Using Regex .   Again, not pretty, but seems to work

Code: [Select]

using System;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace CharCount
{
    class Program
    {
        static int CountMe(String pChar, String pString)
        {
            Regex rx = new Regex("[" + pChar.ToLower() + pChar.ToUpper()+ "]");
            MatchCollection matches = rx.Matches(pString);
            return matches.Count;
        }

        static void Main(string[] args)
        {
            int[] counts = new int[91];
            int[] Testcounts = new int[91];

            using (StreamReader sr = new StreamReader("c:/testfile.txt"))
            {
                String fullFile = sr.ReadToEnd();
                String upper = fullFile.ToUpper();  // CountMe doesn't require this

                for (int i = 65; i < 91; i++)
                {
                    Testcounts[i]= CountMe(Convert.ToChar(i).ToString(), upper);  // there must be a cleaner way to do this

                }
            }


            for (int i = 65; i < 91; i++)
            {
                Console.WriteLine("\nNumber of {0}'s is {1}", Convert.ToChar(i), Testcounts[i]);
            }

            Console.WriteLine("\nHit enter to continue");
            Console.ReadLine();
        }
    }
}




David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4075
Re: Read file, write file
« Reply #13 on: February 07, 2008, 10:04:23 AM »
I have 2 projects I have to get out today, but thanks a bunch everyone.  I definitly have some ideas to read up on now and move forward.  I'll keep you posted on how it goes.
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

SomeCallMeDave

  • Guest
Re: Read file, write file
« Reply #14 on: February 07, 2008, 01:29:47 PM »
I'm a bit bored today so I've been having a play with this task.

Here is a simple version (no exception catching, etc)  with an extension method of the String object that uses LINQ to count the occurences

Code: [Select]

using System;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace CharCount
{
    public static class StringExtension
    {
        internal static int CountChar(this String pString, String pChar)
        {
            IEnumerable<char> query = from s in pString
                                      where s.ToString() == pChar
                                      select s;
            return query.Count();

        }

        internal static int CountChar(this String pString, char pChar)
        {
            IEnumerable<char> query = from s in pString
                                      where s.ToString() == pChar.ToString()
                                      select s;
            return query.Count();

        }
        internal static int CountChar(this String pString, int pIntValOfChar)
        {
            IEnumerable<char> query = from s in pString
                                      where s.ToString() == Convert.ToChar(pIntValOfChar).ToString()
                                      select s;
            return query.Count();

        }

    }//StringExtension

    class Program
    {
        static void Main(string[] args)
        {
            int[] Counts = new int[91];

            using (StreamReader sr = new StreamReader("c:/testfile.txt"))
            {
                String fullFile = sr.ReadToEnd();
                String upper = fullFile.ToUpper();

                //usage of extension method
                int k = upper.CountChar("A");
                int l = upper.CountChar('B');
                int m = upper.CountChar(67);

                for (char j = '0'; j <= '9'; j++)
                {
                    Counts[Convert.ToInt16(j)] = upper.CountChar(j);
                    Console.WriteLine("\nNumber of {0}'s is {1}", j.ToString(), Counts[Convert.ToInt16(j)]);
                }

                for (char j = 'A'; j <= 'Z'; j++)
                {
                    Counts[Convert.ToInt16(j)] = upper.CountChar(j);
                    Console.WriteLine("\nNumber of {0}'s is {1}", j.ToString(), Counts[Convert.ToInt16(j)]);
                }

                Console.WriteLine("\nHit enter to continue");
                Console.ReadLine();

            }

        }
}


C# sure is fun   :-D