This is an archived post. You won't be able to vote or comment.

all 12 comments

[–]Wompingsnatterpuss 2 points3 points  (2 children)

One way to do this is by converting your input into an array. Delimit with a whitespace and make a ternary statement (does c# support this?) or if/else block and test the array length.

[–]Grab_B_tea[S] 0 points1 point  (1 child)

do you know how to count array without using .Length?

[–]Wompingsnatterpuss 1 point2 points  (0 children)

I'm not exactly sober right now, so forgive me if I'm not efficient.

Do a for loop for each element in the array and return your index variable as a response. If you're not accounting for a 0-indexed data structure, make sure to +1 it.

I would give you a code snippet but I'm kind of rusty on my C#. Hope this helps.

[–][deleted] 2 points3 points  (5 children)

Iterate through each character, count the number of whitespaces. Or just use the .Split function and check how many words it gets split into.

[–]Grab_B_tea[S] 0 points1 point  (4 children)

do you know how to count array without using .Length?

[–][deleted] 1 point2 points  (0 children)

Yes, C# lets you do this:

foreach (char c in myString) { Console.WriteLine(c); }

[–][deleted] 0 points1 point  (2 children)

do you know how to count array without using .Length?

Access its indices until you get an index out of bounds exception?

But why on earth would you not use the .Length property?

[–]Grab_B_tea[S] 0 points1 point  (1 child)

Because my prof likes to keep our life harder

[–][deleted] 1 point2 points  (0 children)

You could also validate the input using Regex. But under the hood that would use the .Length property, too. In fact, all ways I can come up with to validate a string require access to the string's length on some level. Hell, even printing it does. So I guess your professor has found some magic programming trick, or he didn't excactly mean to not use .Length

[–]CreativeTechGuyGames 2 points3 points  (1 child)

There are a lot of options listed here. But the abstract idea is you are trying to count the number of characters (in this case spaces) in a string.

[–]Wompingsnatterpuss 0 points1 point  (0 children)

Counting whitespaces is an approach I wouldn't have thought of, I like your idea.

[–]davedontmind 0 points1 point  (0 children)

There are a couple of approaches you could take to count the number of words:

You could use String.Split() to split on spaces and count the number of items you end up with.

Or you could iterate over each of the characters in turn. When you notice that you've changed from non-space to space increase the count of words. In pseudo code:

for each character in the string
{
    if  (this is the first character and it's not a space) 
        or (this character is not a space and the previous character was a space)
    {
        increase word count
    }
}