Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String Problem

Status
Not open for further replies.

NewSchool

Technical User
Dec 9, 2002
2
US
Hey Guys and girls
Im having lots of trouble with this program Im trying to write. I know its very basic, but Im basically teaching myself C.

I need to write a program that reads a string from the operator, counts the number of words in the string, and then displays the count. My teacher is not much of a help and no one around me knows it. Any help you could give me would be greatly appreciated. Thanks again
 
Until someone presents a better solution, you can use strtok() to keep track of a token count using a space as a delimiter.

You can accomplish something similar by having a loop go through the string looking for spaces (and perhaps looking for the first letter after a space is found to eliminate punctuation and double space count errors).

If you choose the second option, I recommend you have a bool spaceFound variable that toggles every time you encounter a space, or find a letter, and a wordCount that increments only when spaceFound is false...

I.E.

if ( space is encountered and spaceFound == false )
{
increment wordCount
spaceFound = true
}

then have an "if" statement reset spaceFound to false upon encountering the first alphabetic character (look up values ANSI character tables).
 
Thanks a ton.....It took me about an hour but I finally got the thing to work RIGHT for me......you know how it always happens.
 
Being that this is posted in the C++ Microsoft forum, another option to use if you ARE using VC++ is CString. Read in the string and put it into a CString object. Remember, well at least when I was learning how to program, that teachers can throw you for a loop. What about the situation of two spaces side by side? you will read that as an extra word. With CString you can loop as follows

// replace 2 spaces with one as long as two exist.
while(myString.Replace(" "," ")
;

then with CString you can keep using the Find function to count the spaces.

Matt

 
I had a feeling there was a better solution, but I opted to answer because no one else was. Expertise means nothing it accompanies silence...

If you took the time to look at the suggested algorithm, you'd see it takes double spaces into account.
 
PS- the algorithm was also designed to handle punctuation quirks, like " Hi :) How's it going?" which would evaluate incorrectly based on a simple space count.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top