Created
October 25, 2014 04:42
-
-
Save sunny1304/e8356997e82f86b03cf1 to your computer and use it in GitHub Desktop.
Word count [seperator: ' ', '\t', '\n', '\r']
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int word_count(const char* str) | |
{ | |
size_t word_count = 0; | |
size_t char_counter = 0; | |
size_t str_length = strlen(str); | |
char* new_str = malloc(str_length+1); | |
strcpy(new_str, str); | |
char* p_new_str = new_str; | |
while(*p_new_str != '\0') | |
{ | |
if ((*p_new_str == ' ') || (*p_new_str == '\t') || (*p_new_str == '\n') || (*p_new_str == '\r')) | |
{ | |
if (char_counter > 0) | |
{ | |
word_count++; | |
p_new_str++; | |
char_counter =0; /* every time a word is found, char_counter is reset to 0 */ | |
} | |
else | |
{ | |
p_new_str++; | |
} | |
} | |
else | |
{ | |
char_counter++; | |
p_new_str++; | |
} | |
} | |
/* word count after the last seperator */ | |
if (char_counter > 0) | |
{ | |
word_count++; | |
} | |
free(new_str); | |
return word_count; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
int wcount; | |
wcount = word_count(argv[1]); | |
printf("%zd\n", wcount); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment