I need to create a method that counts words and lines using specific guidelines and I can't figure it out:

Update the count of words & lines in the file as each character is read
create a void method, CountIt(), to count the lines and words
Parameters: pass in the character by value
pass in a reference to the word count
pass in a reference to the line count
pass in a reference to the bool that tracks if you are "in a word"
Will need a bool variable to keep track WHEN you are IN A WORD or NOT.

bool inWord = true;
int linecount = 0, wordcount = 0;
.
.
.
// calling the CountIt() method (which is in a loop)
CountIt(x, ref linecount, ref wordcount, ref inWord);
.
.
.
// the CountIt() method
private static void CountIt(string x, ref int linecount, ref int wordcount, ref bool inWord)
    {
 
    //count words and lines in here.    
 
    }

I have no clue how to go about this (what the bool should say, what should be in my method). I've been trying to teach myself through reading and other means but no luck.

To count words in a string use Split method and to count number of lines in a file use File.ReadAllLines() method.

linecount = System.IO.File.ReadAllLines(@"C:\file.ext").Length;

To count words in a string use Split method and to count number of lines in a file use File.ReadAllLines() method.

linecount = System.IO.File.ReadAllLines(@"C:\file.ext").Length;

The method for counting lines will work in my case, but for counting words, I have to use a bool variable to keep track when I'm in a word or not. I'm passing that bool by reference, but I don't know what that bool statement should be or what I have to do within that method.

Have a look at my favorite Extension method from MSDN page.

Have a look at my favorite Extension method from MSDN page.

I read about the Extension Methods....it was pretty interesting and could be helpful in the future for me. But my assignment calls for those specifics....sorry. That's why I'm limited to what I can do and I have no clue how to implement a bool and count words that way..my initial post explains.

>pass in a reference to the bool that tracks if you are "in a word"

If you are not interested to use built-in Split method then you have to write your own algorithm. (Iterating Over Each Character in a String).

static void Main()
    {
        string str = "Hello World";
        bool b=false ;
        for (int i = 0; i < str.Length; i++)
        {
            In_A_Word(ref b, str, i);
            Console.WriteLine(b);
        }
    }
    static void In_A_Word(ref bool status, string str, int position)
    {
        if (position >= str.Length)
            status = false;

        if (char.IsWhiteSpace(str[position]))
            status = true;
        else
            status = false;
    }
commented: As always, very helpfull. +8

Output to your code:

False
False
False
False
False
True
False
False
False
False
False

I have no clue what's going on...sorry. Here's all of the code I have in my program:

using System;
using System.IO;
class TEXT
{
    static StreamWriter writer;
    static StreamReader reader;
    static void Main()
    {

        int ch, characters = 0;
        int linecount = 0, wordcount = 0;
        

        // file that is being read in and displayed one character at a time in the console screen.
        reader = new StreamReader("../../../data.txt");
        
        // new file where hex characters will be written to.
        writer = new StreamWriter("../../../s_drcyphert.txt");
        

        do
        {
            //---------------------------------------
            // read one character at a time.
            ch = reader.Read();
            string x = (ch.ToString("x2")) + " ";
            bool status = false;

            //----------------------------------------
            // write each char to the console screen
            Console.Write((char)ch);
            //----------------------------------------

            // count the characters
            characters++;
            //--------------------------------------------------

            // create a method, WriteByte(). use parameters to pass in the character
            // to be written and a reference to the output file.
            WriteByte(x, ref writer);
            CountIt(x, ref linecount, ref wordcount, ref status);
            //---------------------------------------------------

        } while (!reader.EndOfStream);
        reader.Close();
        reader.Dispose();
        // print out all of the count information to the screen.
        Console.WriteLine("");
        Console.WriteLine("-------------------------------------------");
        Console.WriteLine("Number of characters: " + characters.ToString());
        Console.WriteLine("Number of lines: " + linecount);
        Console.WriteLine("Number of words: " + wordcount);
        writer.Close();
       
    }
    // method for counting the words and lines in the file.
    // to count lines, I used the ReadAllLines() method to keep track of how many lines are in the 
    // origonal file.
    static void CountIt(string x, ref int linecount, ref int wordcount, ref bool status)
    {
        linecount = File.ReadAllLines("../../../data.txt").Length;

    }


    static void WriteByte(string w, ref StreamWriter writer)
    {
        writer.Write(w);
    }



}

Try this

StreamReader sr = new StreamReader(Environment.CurrentDirectory + "\\Bhagawat.txt");
            string line = null;
           do
            {
                line = sr.ReadLine();
                
                if ((line != null))
                {
                     MessageBox.show(line);                         //Read line
                    foreach (char cnt in line)
                    {
                        MessageBox.Show(cnt.ToString());          //Read characters
                    }

                }
            } while (!(line == null));
            sr.Close();

I need to use a bool variable to detect if I'm in a word or not....and I'm writing a console program.

you are in my class. XD
I'm trying to figure the same shit out.

Wyatt doesn't really provide the kind of teaching that I expect from a university, the fact that I have to google every concept is piss poor.

Hope you are having an easier time than I am.

you are in my class. XD
I'm trying to figure the same shit out.

Wyatt doesn't really provide the kind of teaching that I expect from a university, the fact that I have to google every concept is piss poor.

Hope you are having an easier time than I am.

you are in my class. XD
I'm trying to figure the same shit out.

Wyatt doesn't really provide the kind of teaching that I expect from a university, the fact that I have to google every concept is piss poor.

Hope you are having an easier time than I am.

I'm doing as much as I can on my own, reading books and online material. but sometimes I have to ask questions on here...It usually helps. The only part I'm stuck on is counting words. I can count the words if there is only 1 whitespace in between, but what if there is multiple tabs/spaces? that's what I cant figure out. What are you having trouble with?

Here is my final result if anyone is interested, please don't copy and paste it when you turn it in.

I have to Google almost everything for his classes, I didn't get the books they almost never help me.

Its all in the countit method, if we are not inaword you don't add to the count ever and if u are not inaword and you read a non-whitespace char it sets the boolean back to true (representing the start of a word)

if we are inaword and we find a white space then we add one to the count and set it to false (simulating the end of a word)

pretty sure you can add to the count in either place (beginning or end), i had to start the counts for line and word at 1, not sure why. might be wrong on something. it produces the result he wants tho.

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

namespace TEXT {
    class Program {
        
        /// <summary>
        /// Main method that loops while there is still chars to be read and processes the character for output to a file
        /// </summary>
        static void Main(string[] args) {
            // Set initial counters to the correct values
            int totalchars = 0;
            int totalwords = 1;
            int totallines = 1;
            bool inaword = false;
            // Create a FileInfo instance representing an existing text file and instantiate a StreamReader to read from the text file.
            FileInfo MyFile = new FileInfo(@"../../../data.txt");
            StreamReader textreader = MyFile.OpenText();
            // Instantiate new StreamWriter that points to a file where hex characters will be written to.
            StreamWriter textwriter = new StreamWriter("../../../s_phallicgore.txt");
            // Loop while there is still chars to be read and process the character for output
            do {
                // Read a single character. make some converted variables thati might use
                int readchar = textreader.Read();
                char charchar = (char)readchar;
                // Write the character to the console and add one to the char count
                Console.WriteLine(charchar); 
                totalchars++;
                // Loop while there is still chars to be read and process the character for output
                WriteByte(readchar, ref textwriter);
                CountIt(readchar, ref inaword, ref totalwords, ref totallines);
            } while (textreader.EndOfStream == false);
            // Close Read/Write to files
            textwriter.Close();
            textreader.Close();
            // Print the result to the console
            WriteEnd(totalchars, totalwords, totallines);
        }

        /// <summary>
        /// Method to write the current char to the textwriter document using HEX values
        /// </summary>
        /// <param name="readchar"></param>
        /// <param name="textwriter"></param>
        static void WriteByte(int readchar, ref StreamWriter textwriter) {
            // make a new output string to fill
            string outputstringhex = "";
            // if we read in an A or D value add a 0 before writing to the document
            if (readchar.ToString("X") == "A" || readchar.ToString("X") == "D") {
                outputstringhex += "0";
                outputstringhex += readchar.ToString("X");
            }
            else {
                outputstringhex += readchar.ToString("X");
            }
            // add a space and write the string to the file
            outputstringhex += " ";
            textwriter.Write(outputstringhex);
        }

        /// <summary>
        /// Print out the ending information about the file to the console
        /// </summary>
        /// <param name="totalchars">integer representing the total chars</param>
        /// <param name="totalwords">integer representing the total words</param>
        /// <param name="totallines">integer representing the total lines</param>
        static void WriteEnd(int totalchars, int totalwords, int totallines) {            
            Console.WriteLine("");
            Console.WriteLine("=========================================================");
            Console.WriteLine("Number of Characters: " + totalchars.ToString());
            Console.WriteLine("Number of Lines: " + totallines.ToString());
            Console.WriteLine("Number of Words: " + totalwords.ToString());
            Console.WriteLine("");
        }

        /// <summary>
        /// This method is used by the main method each loop to keep track of how many words and lines are being read in.
        /// </summary>
        /// <param name="readchar">the character that is being passed in during hte loop</param>
        /// <param name="inaword">boolean variable representing if we are inside a word</param>
        /// <param name="totalwords">ref to the total word count</param>
        /// <param name="totallines">ref to the total line count</param>
        static void CountIt(int readchar, ref bool inaword, ref int totalwords, ref int totallines)
        {
            // if we read a line return char then add to the total lines
            if (readchar == 13) {
                totallines++;
            }
            // check if we are inaword and read white space then proceed to add to the count and set inaword to false
            if (inaword) {
                if (readchar == 13 || readchar == 32 || readchar == 9 || readchar == 10)) {
                    totalwords++;
                    inaword = false;
                }
            }
            // if !inaword and we are not reading white space set the inaword to true
            else if (!inaword) {
                if (readchar != 13 && readchar != 32 && readchar != 9 && readchar != 10) {
                    inaword = true;
                }
            }            
        }
    }
}

thats pretty much what I had, except I didn't create a method for printing out all of the count information, I just did that in Main(). Also, I converted my char to a string so I could format it into hex characters...it seemed easiest for me. For example, my if statements would look like this in the CountIt() method:

if (letters == ' ' || letters == '\t' || letters == '\n')
        {
            status = false;
            wordcount++;

        }

And don't worry, your intellectual property is yours and yours only... I wouldn't recommend anyone copying someone else's code because you wouldn't learn anything anyways. It's interesting to see how other people approach the same problem.

the readchar variable i used is an integer when you read it in, so you can use the tostring method with the parameter "X" to convert it directly to a hex value

readchar.ToString("X");

but it was only giving me A and D so i had to at 0 to the string

I have to Google almost everything for his classes, I didn't get the books they almost never help me.

What book(s) does the class ask you to get?

What book(s) does the class ask you to get?

Essential C# 4.0 and Primer C++

Looking at the book they seem to jump from topic to topic with no regards to grouping like items together. You'd be better off getting C# 4.0 in a Nutshell

Looking at the book they seem to jump from topic to topic with no regards to grouping like items together. You'd be better off getting C# 4.0 in a Nutshell

I have LINQ Pad with 'C# in a NutShell 4.0 samples. I've been messing around with it, it seems to help a little bit.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.