LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 04-23-2004, 02:48 PM   #1
Rico16135
Member
 
Registered: Aug 2003
Location: Texas, USA
Distribution: Slackware 9.1, SuSE 9.1
Posts: 245

Rep: Reputation: 30
C++ "counting words in a string"


In the book I am reading the suggested exercise is to write a function to count the number of words in a string. Then include what I define as a word in my documentation. Well, I haven't done alot with strings so I'm feeling a bit overwhelmed.

For this exercise a word should be:
A series of alphabetical characters
Seperated by spaces or commas
(Any other suggestions? I could get real thorough, but its just an exercise.)
Also, I am not clear how to proceed. Creating the function is not hard, but how do I parse a string??

Be patient I'm relatively new to programming.
 
Old 04-23-2004, 03:02 PM   #2
h/w
Senior Member
 
Registered: Mar 2003
Location: New York, NY
Distribution: Debian Testing
Posts: 1,286

Rep: Reputation: 45
hi, maybe i can write something and show ya when i get home from work. i would suggest you go through this link quick on C++.

http://www.research.att.com/~bs/bs_faq2.html

it's got links outside from there, which are worth a read too.
 
Old 04-23-2004, 04:08 PM   #3
zekko
Member
 
Registered: Aug 2003
Location: Canada
Distribution: Slackware, debian
Posts: 76

Rep: Reputation: 15
Since this is a exercise, you should write the actual code, but it's not too hard.

Get a string from the user, then loop through the string until '\0'
When looping, look for spaces, commas, tabs, newlines (if you keep getting input until EOF) and if found, use a variable to track how many times (count++).

Hope this helps ...
 
Old 04-23-2004, 04:25 PM   #4
Mega Man X
Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 63
It has been a while since I used C++, so I won't post any real code since it will be wrong . But search for the function len(). Len counts the number of characters(length) in a string. Create two variables:

int numberWords;
String yourString;

Then make a for-next loop:

for (int i = 0; i <= yourString.len(); i++) {
...
// inside this loop, check to see if the hole string has "space" or "comma"
// if it has, then increase numberWords by one
// numberWords = numberWords +1
}

// show the results:

cout << numberWords << end;

I think you got the idea. The code above is all wrong for sure, but it's for you to get an idea
 
Old 04-23-2004, 05:01 PM   #5
zekko
Member
 
Registered: Aug 2003
Location: Canada
Distribution: Slackware, debian
Posts: 76

Rep: Reputation: 15
Oh yeah, you'll probably want to make some variable to tell if you're inside a word or not. If you are inside a word and a space, comma etc comes up, now you're outside. When a character comes up thats not some kind of space, you're inside the word and can upper the amounts of counted words.

Heh, I hope this makes sense ...
 
Old 04-23-2004, 05:43 PM   #6
itsme86
Senior Member
 
Registered: Jan 2004
Location: Oregon, USA
Distribution: Slackware
Posts: 1,246

Rep: Reputation: 58
I'll do an example for you in C. It should compile using a C++ compiler, but it's not C++ code per se

Code:
itsme@dreams:~/C$ cat countwords.c
#include <stdio.h>
#include <string.h>

#define IS_PUNC(c) ((c) == ' ' || (c) == '.' || (c) == ',')

int word_count(char *str)
{
  int count = 0;
  char *s;

  // Skip leading punctuation and white-space
  while(IS_PUNC(*str))
    str++;
  s = str;

  while(*str)
  {
    while(*s && !IS_PUNC(*s))
      s++;
    if(str - s)
      count++;
    while(IS_PUNC(*s))
      s++;
    str = s;
  }

  return count;
}

int main(int argc, char **argv)
{
  if(argc != 2)
  {
    puts("Usage: countwords <string>");
    return 1;
  }

  printf("%d\n", word_count(argv[1]));
  return 0;
}
itsme@dreams:~/C$ ./countwords "This is a test, this is only a test."
9
 
Old 04-26-2004, 04:49 PM   #7
Rico16135
Member
 
Registered: Aug 2003
Location: Texas, USA
Distribution: Slackware 9.1, SuSE 9.1
Posts: 245

Original Poster
Rep: Reputation: 30
/* Thanks all for the advice and help. I have made a version myself, but I am getting a compiler error. It would be great if ya'll could look at it. I think I've just been missing a small fundamental issue, hence my error. */


#include <string.h>
#include <iostream.h>

main() {

char user_string[100];
int words_in_string = 0;
cout << "This program takes a sentence input by the user and returns" << '\n';;
cout << " the amount of words." << '\n';
cout << "Please input now: ";
cin.getline(user_string, sizeof(user_string)); // gets the string to use

int word_count(char input_string); // calling the function
words_in_string = word_count(user_string[100]); // thought this would work

if(words_in_string == 1) {
cout << "There is " << words_in_string << " word in the string." << '\n';
}
else {
cout << "There are " << words_in_string << " words in the string." << '\n';
}
return (0);
}
/*****************************************************************
* word_count -- counts words in a given string. Considers a period, comma and space *
* bar as word seperators. Uses ASCII code to determine. *
* *
* Parameters *
* some string *
* *
* Returns *
* num_words -- number of words in string *
******************************************************************/
int word_count(char input_string) // funtion to find how many words
{
int counter = 0;
char variable_x;
int num_words = 0;

for (variable_x = input_string[0]; variable_x != '\0'; counter++) { // looping through string
if((variable_x == 32) || (variable_x == 46) || (variable_x == 44)) { // looking for spaces
num_words++;
}
variable_x = input_string[counter];
}
return (num_words); // answer to how many words.
}



// my compiler errors were: (c++ source file was called 9-1.cc Both errors within the function)
// the first error was the beginning of the for loop, the second was "variable_x = input_string[counter]; " Can I not do this?

//9-1.cc:38: error: invalid types `char[int]' for array subscript
//9-1.cc:42: error: invalid types `char[int]' for array subscript

Last edited by Rico16135; 04-26-2004 at 04:51 PM.
 
Old 04-26-2004, 04:52 PM   #8
Rico16135
Member
 
Registered: Aug 2003
Location: Texas, USA
Distribution: Slackware 9.1, SuSE 9.1
Posts: 245

Original Poster
Rep: Reputation: 30
forgive me, I think the word wrap screwed up some of the code. Especially the "{}" Excuse the code. Just look over the concepts if you could. Thanx guys.

Last edited by Rico16135; 04-26-2004 at 04:54 PM.
 
Old 05-04-2009, 10:21 AM   #9
thallium205
LQ Newbie
 
Registered: May 2009
Posts: 1

Rep: Reputation: 0
Talking Try this

Code:
#include <iostream>
#include <string>
using namespace std;

int main()
{
	int i, numspaces;
	char nextChar;
	string msg;

	numspaces=1;

	cout << "Type in a string\n";
	getline(cin, msg);

	// checks each character in the string
	for (i=0; i<int(msg.length()); i++)
	{
		nextChar = msg.at(i); // gets a character
		if (isspace(msg[i]))
			numspaces++;
	}
	cout << "\nThere are " << numspaces << " words in this string.";
	cin.ignore();
	return 0;
}
 
Old 05-04-2009, 05:07 PM   #10
rriggs
Member
 
Registered: Mar 2009
Location: Colorado, US
Distribution: Fedora 13, Fedora 14, RHEL6 Beta
Posts: 46

Rep: Reputation: 17
Iterators make quick work of the problem.

Code:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>

using namespace std;

int main()
{
	string msg;

	cout << "Type in a string\n";
	getline(cin, msg);
	
	istringstream ostr(msg);
	istream_iterator<string> it(ostr);
	istream_iterator<string> end;
	
	size_t words = 0;
	while (it++ != end) words++;

	cout << "\nThere are " << words << " words in this string." << endl;

	return 0;
}
 
Old 05-06-2009, 11:56 AM   #11
amysaraantony
Member
 
Registered: Apr 2009
Posts: 42

Rep: Reputation: 16
Googling for this should get you all the code you want my friend.


Debian

Last edited by amysaraantony; 05-15-2009 at 08:14 PM.
 
Old 05-06-2009, 12:30 PM   #12
dmail
Member
 
Registered: Oct 2005
Posts: 970

Rep: Reputation: Disabled
Please stop keeping this thread alive it was started over five years ago and your comment did not add anything of value. In fact from looking at your post history, I do not think any of your posts have added value
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
ssh login problem RedHat AS3 ("Did not receive identification string from") spaniel Linux - Security 1 07-03-2005 06:50 AM
how to actually write words in "scribus"? ungua Linux - Software 6 11-28-2004 07:59 AM
Google Ad-Words advertises MS's "Get the fact campaign" on LQ? Squall General 6 03-23-2004 10:47 PM
why my "htdig" only search serail words? beelzebub888 Linux - Software 0 12-28-2002 05:20 AM
How can I catch some "KEY WORDS" from a text file without opening it? yuzuohong Linux - General 1 06-14-2002 09:27 PM


All times are GMT -5. The time now is 05:52 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration