-
Checking number of words
Hello all,
Could somebody help me please with my code? I am having trouble with the NumWords() function. I need to be able to count how many words are in my character array. The catch is that counting the number of spaces will not be enough since you can have a consecutive spaces between "words". This is what I have so far.
Code:
// Program Description: This is a header file for the Sentence class
#ifndef SENTENCE_H
#define SENTENCE_H
#include <iostream>
#include <cstring>
// sets number of elements string array can have to constant for easy modification
const int SIZE = 200;
class Sentence
{
public:
Sentence();
Sentence(char *s);
void Input();
char *GetSentence() const;
void Append(char *s);
int Size();
void Clear();
int NumWords();
void Insert(char *s, int index);
void Delete(int index, int num_chars);
private:
char string[SIZE];
int track; // tracking variable
};
#endif
Code:
int Sentence::NumWords()
// returns the number of words in the stored string
{
int word_count;
char *s;
s = string;
while(*s != '\0'){
if ((*s == ' ')||(*s == '\t'))
word_count++;
*s++;
}
return word_count;
}
Thank you in advance.
-
You might also want to look up strtok, which is found in the string header file. You could do it without strtok but that was the first thing that came to my crazy mind :D
-
Need help on Append
Hello all,
I got count num words but I need help on the Append(char *s) function. Please take a look at this and tell me if I am on the right track
Code:
void Sentence::Append(char *s)
// Appends a string (given in parameter) to the end of the stored string
{
// First, we read go to the end of string[]
int i = 0;
while (string[i] != '\0'){
(string[i])++;
i++;
}
for ( ; string = *s; string++, s++)
// empty statement
}
Thank you.
-
I am sure that this looks a little bit better right?
Code:
void Sentence::Append(char *s)
// Appends a string (given in parameter) to the end of the stored string
{
int i = 0;
// a similar example is the first example in the online classroom notes(Ex. 05_21.cpp)
while(string[i] != '\0')
++i;
// Secondly, we concatenate whatever the string s has to the character array
for (; string[i] = *s; i++,s++)
{}// empty statement
}
One more final thing. How do I check that I do not go out-of-bound of my array when I do the append? In other words, when I initially input a string into my string[SIZE] array, I can assume that it will meet the size constraint but when I append it I cannot make any such assumption. How do I make sure that my string[SIZE] array will not go out of my bound after I appended the string into my character array? Thank you.