I need to write a function that will count words in a string. For the purpose of this assignment, a \"word\" is defined to be a sequence of non-null, non-whitespace characte
I found the posted question after finishing my function for a C class I'm taking. I saw some good ideas from code people have posted above. Here's what I had come up with for an answer. It certainly is not as concise as other's, but it does work. Maybe this will help someone in the future.
My function receives an array of chars in. I then set a pointer to the array to speed up the function if it was scaled up. Next I found the length of the string to loop over. I then use the length of the string as the max for the 'for' loop. I then check the pointer which is looking at array[0] to see if it is a valid character or punctuation. If pointer is valid then increment to next array index. The word counter is incremented when the first two tests fail. The function then will increment over any number of spaces until the next valid char is found. The function ends when null '\0' or a new line '\n' character is found. Function will increment count one last time right before it exit to account for the word preceding null or newline. Function returns count to the calling function.
#include <ctype.h>
char wordCount(char array[]) {
char *pointer; //Declare pointer type char
pointer = &array[0]; //Pointer to array
int count; //Holder for word count
count = 0; //Initialize to 0.
long len; //Holder for length of passed sentence
len = strlen(array); //Set len to length of string
for (int i = 0; i < len; i++){
//Is char punctuation?
if (ispunct(*(pointer)) == 1) {
pointer += 1;
continue;
}
//Is the char a valid character?
if (isalpha(*(pointer)) == 1) {
pointer += 1;
continue;
}
//Not a valid char. Increment counter.
count++;
//Look out for those empty spaces. Don't count previous
//word until hitting the end of the spaces.
if (*(pointer) == ' ') {
do {
pointer += 1;
} while (*(pointer) == ' ');
}
//Important, check for end of the string
//or newline characters.
if (*pointer == '\0' || *pointer == '\n') {
count++;
return(count);
}
}
//Redundent return statement.
count++;
return(count);
}
See the following example, you can follow the approach : count the whitespace between words .
int words(const char *sentence)
{
int count=0,i,len;
char lastC;
len=strlen(sentence);
if(len > 0)
{
lastC = sentence[0];
}
for(i=0; i<=len; i++)
{
if((sentence[i]==' ' || sentence[i]=='\0') && lastC != ' ')
{
count++;
}
lastC = sentence[i];
}
return count;
}
To test :
int main()
{
char str[30] = "a posse ad esse";
printf("Words = %i\n", words(str));
}
Output :
Words = 4
bool isWhiteSpace( char c )
{
if( c == ' ' || c == '\t' || c == '\n' )
return true;
return false;
}
int wordCount( char *string )
{
char *s = string;
bool inWord = false;
int i = 0;
while( *s )
{
if( isWhiteSpace(*s))
{
inWord = false;
while( isWhiteSpace(*s) )
s++;
}
else
{
if( !inWord )
{
inWord = true;
i++;
}
s++;
}
}
return i;
}
#include <ctype.h> // isspace()
int
nwords(const char *s) {
if (!s) return -1;
int n = 0;
int inword = 0;
for ( ; *s; ++s) {
if (!isspace(*s)) {
if (inword == 0) { // begin word
inword = 1;
++n;
}
}
else if (inword) { // end word
inword = 0;
}
}
return n;
}
this is a simpler function to calculate the number of words
int counter_words(char* a){`
// go through chars in a
// if ' ' new word
int words=1;
int i;
for(i=0;i<strlen(a);++i)
{
if(a[i]==' ' && a[i+1] !=0)
{
++words;
}
}
return words;}
You needed
int words(const char sentence[])
{
}
(note braces).
For loops go with ;
instead of ,
.
Without any disclaimer, here's what I'd have written:
See it live http://ideone.com/uNgPL
#include <string.h>
#include <stdio.h>
int words(const char sentence[ ])
{
int counted = 0; // result
// state:
const char* it = sentence;
int inword = 0;
do switch(*it) {
case '\0':
case ' ': case '\t': case '\n': case '\r': // TODO others?
if (inword) { inword = 0; counted++; }
break;
default: inword = 1;
} while(*it++);
return counted;
}
int main(int argc, const char *argv[])
{
printf("%d\n", words(""));
printf("%d\n", words("\t"));
printf("%d\n", words(" a castle "));
printf("%d\n", words("my world is a castle"));
}