Counting the vowels and characters in each word of a sentence - c

I have been trying to figure out how to count the vowels and characters in each word of a sentance.
For example
In hello there sentence
hello : 5 characters, 2 vowels
there : 5 characters, 2 vowels. I have seen the code for doing the same thing for a full sentence. But not word by word.
Below is the coding I've been working on
int main() {
char str[512] = "hello there", word[256];
int i = 0, j = 0, v, h;
str[strlen(str)] = '\0';
/* checking whether the input string is NULL */
if (str[0] == '\0') {
printf("Input string is NULL\n");
return 0;
}
/* printing words in the given string */
while (str[i] != '\0') {
/* ' ' is the separator to split words */
if (str[i] == ' ')
{
for (h = 0; word[h] != '\0'; ++h)
{
if (word[h] == 'a' || word[h] == 'e' || word[h] == 'i' || word[h] == 'o' || word[h] == 'u')++v;
}
printf("\nVowels: %d", v);
word[j] = '\0';
printf("%s\n", word);
j = 0;
}
else
{
word[j++] = str[i];
}
i++;
}
word[j] = '\0';
/* printing last word in the input string */
printf("%s\n", word);
return 0;
}
The input will be all lower case. I'm having a hard time figuring this out.
While running the code I'm not getting the vowels count. I'm able to split the sentence. But vowel counting is not happening.

One fairly simple approach:
#include <stdio.h>
const char* s(int n)
{
return n == 1? "" : "s";
}
void count (const char* str)
{
for (int i = 0;;)
for (int v = 0, w = i;;)
{
int len;
char c = str[i++];
switch (c)
{
case 'a': case 'e': case 'i': case 'o': case 'u':
v++;
default:
continue;
case ' ': case '\t': case '\n': case '\0':
len = i - 1 - w;
printf("'%.*s': %d character%s, %d vowel%s\n", len, str+w, len, s(len), v, s(v));
if (c)
break;
else
return;
}
break;
}
}
int main(void)
{
count("My words with vowels");
return 0;
}

This sounds an awful lot like a homework assignment..
here's some pseudo-code <-- below will NOT run as is. Just to show logic.
int c = 0;
int v = 0;
for (int i = 0; i < lengthOfSentence; i++){
if (stringName[i] == '\0') { //optionally '\n' may be more suitable
return;
}
if (stringName[i] == ' '){
print previousWord // + c, v in whatever format you want
c = 0;
v = 0;
}
if (stringName[i] == vowel) { //you can do this part like in your code
word[v+c] = stringName[i]; //get current char and add to next slot
v++;
}
else {
word[v+c] = stringName[i];
c++;
}
beyond that it's minute details like realizing v+c will give you total word length when printing, etc..

Try this code. it might help you
#include<stdio.h>
int main() {
char str[512] = "hello there", word[256];
int i = 0, j = 0, v=0,h; // you didn't initialize v to 0
str[strlen(str)] = '\0';
/* checking whether the input string is NULL */
if (str[0] == '\0') {
printf("Input string is NULL\n");
return 0;
}
/* printing words in the given string */
while (str[i] != '\0') {
/* ' ' is the separator to split words */
if (str[i] == ' ' ) {
for (h = 0; word[h] != '\0'; h++) {
if (word[h] == 'a' || word[h] == 'e' || word[h] == 'i' || word[h] == 'o' || word[h] == 'u')
v++;
}
printf("%s :", word);
printf(" %d chracters,",strlen(word));
printf(" %d Vowels.\n", v);
j = 0; v=0;
word[j] = '\0';
} else {
word[j++] = str[i];
word[j] = '\0';
}
i++;
}
/* calculating vowels in the last word*/ // when NULL occurs, Wont enter into while loop.
for (h = 0; word[h] != '\0'; h++) {
if (word[h] == 'a' || word[h] == 'e' || word[h] == 'i' || word[h] == 'o' || word[h] == 'u')
v++;
}
printf("%s :", word);
printf(" %d chracters,",strlen(word));
printf(" %d Vowels.\n", v);
return 0;
}

What you can probably do is, you can print the count for the characters and vowels when you encounter a " "(space) and then reset the counters. That way, you can find the characters and vowels for each word of the sentence.

If you understand the logic for doing this throughout a sentence, then you can also do it in single words by simple breaking the sentence into individual word and applying the same logic to each word. You can use the fact that words are separated by a space (or multiple, maybe) to break down the sentence into words.

Related

Program to count the total number of vowels, consonants and words and ask for a user again for check for a letter for a string

Program to count the total number of vowels, consonants, words and ask for a user again to check how many times a word has been used in that sentence checking in a string.
At this point my code does checks vowels and consonants and after this program has to ask for a word to the user to input a word and check how many times ıts been used in that sentence.
#include <stdio.h>
void main() {
char sentence[80];
int i, vowels = 0, consonants = 0, special = 0;
printf("Enter a sentence \n");
gets(sentence);
for (i = 0; sentence[i] != '\0'; i++) {
if ((sentence[i] == 'a' || sentence[i] == 'e' ||
sentence[i] == 'i' || sentence[i] == 'o' ||
sentence[i] == 'u') ||
(sentence[i] == 'A' || sentence[i] == 'E' ||
sentence[i] == 'I' || sentence[i] == 'O' ||
sentence[i] == 'U')) {
vowels = vowels + 1;
} else {
consonants = consonants + 1;
}
if (sentence[i] == '\t' ||sentence[i] == '\0' || sentence[i] == ' ') {
special = special + 1;
}
}
consonants = consonants - special;
printf("No. of vowels in %s = %d\n", sentence, vowels);
printf("No. of consonants in %s = %d\n", sentence, consonants);
}
Here are some problems in your code:
void main() is invalid: you should write int main()
gets(sentence); is risky as input longer than 79 bytes will cause a buffer overflow. This function is a security flaw and has been removed from current versions of the C Standard. You should use fgets() instead and check the return value.
you only test for TAB and SPACE as special characters, so any punctuation will be counted as consonant letters.
you do not count the number of words
you only implement the first part of the assignment.
Here is a modified version using ancillary functions:
#include <stdio.h>
#include <string.h>
int is_letter(char c) {
// Assuming ASCII
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
int is_vowel(char c) {
return c != '\0' && strchr("aeiouAEIOU", c) != NULL;
}
int main() {
char sentence[80];
printf("Enter a sentence \n");
if (fgets(sentence, sizeof sentence, stdin)) {
int i, vowels = 0, consonants = 0, words = 0;
char c, lastc = 0;
for (i = 0; sentence[i] != '\0'; i++) {
c = sentence[i];
if (is_letter(c)) {
if (is_vowel(c)) {
vowels = vowels + 1;
} else {
consonants = consonants + 1;
}
if (!is_letter(last)) {
words = words + 1;
}
}
last = c;
}
printf("No. of vowels = %d\n", vowels);
printf("No. of consonants = %d\n", consonants);
printf("No. of words = %d\n", words);
// implement the rest of the assignment...
}
return 0;
}

Program to find how many words in a text don't contain a specific character

The following program runs without printing anything on the screen, maybe because the loop goes over the null character. I can't understand why and how this happens, and how to fix it.
//program to find how many word in the text doesn't contain p char
#include<stdio.h>
#include<stdbool.h>
#define space ' '
void find_word(char s[]) {
bool wordfound = false;
int i, j = 0, word = 0;
i = 0;
while (s[i]) { //s[i]!='\0' does not
if (s[i] != 'p' && s[i + 1] != space) { //for the first word
wordfound = true;
word++;
}
wordfound = false;
if (s[i] == space && s[i + 1] != space) { //for more than one word in the text
for (j = i + 1; s[j] != space; j++)
if (s[j] != 'p' && s[j + 1] != space)
wordfound = true;
}
if (wordfound) {
word++;
}
wordfound = false;
i = j;
i++;
} //end while loop
printf("Number of words not contain p character%d\n\n", word);
}
int main(void) {
char s[] = {"pppp zzzz ppp ssss dfg sfsfdsf"};
find_word(s);
return 0;
}
There are a few problems with this code, but the main one is that inside the loop you assign j to i which causes the infinite loop as the while(s[i]) condition is never met. Why don't you try to make it simple, like so:
//program to find how many word in the text doesn't contain p char
#include<stdio.h>
#include<stdbool.h>
#define space ' '
void find_word(char s[]) {
bool is_in = false;
short words_count = 0, i = 0;
while (s[i]) {
if (s[i] == 'p') { // if this letter is a 'p', mark the word
is_in = true;
}
if (s[i] == space) { // if it's end of word
if (!is_in) { // check if 'p' is present and increase the count
words_count++;
}
is_in = false;
}
i++;
}
if (!is_in) { // check if the last word has 'p'
words_count++;
}
printf("no. of words without p is %d\n", words_count);
}
int main(void) {
char s[] = {"pppp zzzz ppp ssss dfg sfsfdsf"};
find_word(s);
return 0;
}
You appear to have your for-loop terminating condition set to be unsatisfiable given your input.
if (s[i] == space && s[i + 1] != space) { //for more than one word in the text
for (j = i + 1; s[j] != space; j++)
if (s[j] != 'p' && s[j + 1] != space)
wordfound = true;
}
Here you are checking for a leading space in your input string. If you find it you then increment your index checking until you reach another space. What if your string doesn't have a trailing space?
Instead try to have a second condition for null and space to terminate the loop:
if (s[i] == space && s[i + 1] != space) { //for more than one word in the text
for (j = i + 1; s[j] != '\0' && [j] != space; j++)
if (s[j] != 'p' && s[j + 1] != space)
wordfound = true;
}
And then you set:
wordfound = false;
i = j;
i++;
} //end while loop
This will keep re-setting your loop, I'm not clear on your reasoning for this but that will run your loop indefinitely.
If you make these edits your code terminates:
#include<stdio.h>
#include<stdbool.h>
#define space ' '
void find_word(char s[]) {
bool wordfound = false;
int i, j = 0, word = 0;
i = 0;
while (s[i]) { //s[i]!='\0' does not
if (s[i] != 'p' && s[i + 1] != space) { //for the first word
wordfound = true;
word++;
}
wordfound = false;
if (s[i] == space && s[i + 1] != space) { //for more than one word in the text
for (j = i + 1; s[j] && s[j] != space; j++)
if (s[j] != 'p' && s[j + 1] != space)
wordfound = true;
}
if (wordfound) {
word++;
}
wordfound = false;
i++;
} //end while loop
printf("Number of words not contain p character%d\n\n", word);
}
int main(void) {
char s[] = {"pppp zzzz ppp ssss dfg sfsfdsf"};
find_word(s);
return 0;
}
Output:
Number of words not contain p character24

Count how many times a word is used. C

I am trying to count the number of loops and emptylines in a string entered by a user. So here is the way I did it:
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
int main(void) {
int i, lines, loopF = 0, loopW = 0, loopDW = 0, empty = 0;
char *p, str[200];
const char test[10] = "while";
char *f;
printf("Enter a string. Ctrl+Z for exit.\n");
while (fgets(str, 200, stdin) != NULL) {
if (f = strstr(str, test)) { //first way
loopW++;
}
for (i = 0; i < strlen(str); i++) {
// count loops
if (str[i] == 'f' && str[i + 1] == 'o' && str[i + 2] == 'r') {
loopF++;
}
if (str[i] == 'w' && str[i + 1] == 'h' && str[i + 2] == 'i'
&& str[i + 3] == 'l' && str[i + 4] == 'e') { // second way
loopW++;
}
if (str[i] == 'd' && str[i + 1] == 'o') {
loopDW++;
if (loopDW >= 1)
loopW--;
}
}
// count empty lines
p = str;
lines = 0;
while (*p != '\n') {
if (*p != ' ') {
lines = 1;
}
p++;
}
if (!lines) {
empty++;
lines = 0;
}
}
printf("---------------------\n");
printf(" Empty lines: %d \n\n", empty);
printf(" Number of loops:\n");
printf(" For: %d \n", loopF);
printf(" While: %d \n", loopW);
printf(" Do/While: %d \n", loopDW);
printf("---------------------\n");
return 0;
}
I did it for 2 ways only for "while" to test but when a user types "whilethis" or "thiswhile" it counts it(which is not what I want). I want when there is only a while(a loop) to be counted and not with other symbols but i have no idea how to do it. Same is for do/while and for loops. Any help here? :)
The proper solution also needs to handle strings and comments
print("I have no for() loops")
/* commented out for() loop */
char* c = "for()\"loop\\";
If you do not care about this, and really want to use plain C, I would recommend "strtok" function which splits string into the words using delimiters (which would be basically all non-alphanumeric symbols in your case -- space, brackets, comma, etc...). Then once you have words, you can just strcmp() them with "do", "while" or "for"

Erase blank spaces between string in C

So, I am trying to remove the blanks spaces from a sting input by the user. I already have an option where the program counts the vowels and inverts the string. The one where I need help starts with //espaços. What I did was something like: if the "palavra" string, the original one, has a space (' ') in any position, the new string with no space will have the next char from the string "palavra" in that position:
/*palavra = " o l a _ o l a"
[0][1][2][3][4][5][6]
palavra3 = "o l a o l a"
[0][1][2][3][4][5]*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(void) {
char palavra[10];
char palavra2[10];
char palavra3[10];
int i;
int vogais = 0;
int j;
int k;
int espaco = 0;
printf("Introduza uma string: \n");
scanf("%[^\n]", palavra);
//vogais
for (i = 0; palavra[i] != '\0'; i++) {
if (palavra[i] == 'a' || palavra[i] == 'e' || palavra[i] == 'i' ||
palavra[i] == 'o' || palavra[i] == 'u' ||
palavra[i] == 'A' || palavra[i] == 'E' || palavra[i] == 'I' ||
palavra[i] == 'O' || palavra[i] == 'U')
vogais ++;
// else
// printf("");
}
printf("Vogais: %i", vogais);
//invertida
for (i = 0; palavra[i] != '\0'; i++);
{
k = i-1;
}
for (j = 0; j <= i-1; j++) {
palavra2[j] = palavra[k];
k--;
}
printf("\nString invertida: %s", palavra2);
//espaços
for (i = 0; palavra[i]; i++) {
if (palavra[i] == ' ')
palavra3[i] = palavra[i + 1];
//espaco++;
}
// printf("\nNumero de espacos: %i", espaco);
printf("\nString sem espacos: %s", palavra3);
}
Remove the extra ; at the end of for (i = 0; palavra[i] != '\0'; i++);
With the extraneous ;, the loop is empty, the following code executes once with i equal to strlen(palavra).
You can avoid this kind of silly bug by using the Kernighan and Ritchie indentation style: put the { at the end of the line with the if, for, while, do or switch statement. This makes it much less likely to type a spurious ; between the control statement and its block.
To remove the spaces, use the 2 finger method:
//espaços
for (i = j = 0; palavra[i]; i++) {
if (palavra[i] != ' ') {
palavra3[j++] = palavra[i];
}
}
palavra3[j] = '\0'; // set the null terminator
Keep a counter of the new string length k ,check if a character is a space, if it is a space ignore it else increment k and add that character to new string.Example-
int k = 0; //k will be the new string length after the loop
for (int i = 0; palavra[i] != '\0'; i++)
{
if (palavra[i] != ' ')
{
palavra3[k++] = palavra[i];
}
}
palavra3[k] = '\0';
This example also works in the case of multiple consecutive spaces.

Count word in string

I'm trying to write a function to count occurrences of a particular word in a string. For example: Given string -
"Stop, time to go home. Todo fix me."
Letters "to" appeared three times (twice in different words); however, the word "to" appears only once. What should I do to count only word "to" (if will appear in string more times then count every single one). Any advice?
This is the code I was trying and playing around.
int word(char inputLine[]) {
int word = 0, i = 0, j = 0;
for (i = 0; inputLine[i] != '\0'; i++) {
if (inputLine[i] == 't' || inputLine[i] == 'o' || inputLine[i] != ' ') {
word++;
}
}
return word;
}
Try this:
int word(char inputLine[]) {
int word = 0, i = 0;
// stop before the last char
for (i = 0; inputLine[i] != '\0' && inputLine[i+1] != '\0'; i++) {
// is (T or t) and (O or o)
if ((inputLine[i] == 't' || inputLine[i] == 'T') && (inputLine[i+1] == 'o' || inputLine[i+1] == 'O')) {
// after the 'to' is not a letter
if ((inputLine[i+2] < 'a' || inputLine[i+2] > 'z') &&
(inputLine[i+2] < 'A' || inputLine[i+2] > 'Z')) {
// before is not a letter (or this is the start of the string)
if (i == 0 ||
((inputLine[i-1] < 'a' || inputLine[i-1] > 'z') &&
(inputLine[i-1] < 'A' || inputLine[i-1] > 'Z'))) {
word++;
}
}
}
}
return word;
}
The simplest way would be to use strtok. But, if you'd like to do it all by hand, the following will work. Although you only wanted the "to" this will work for any search string:
#include <stdio.h>
// word -- get number of string matches
int
word(char *input,char *str)
// input -- input buffer
// str -- string to search for within input
{
int chr;
int prev;
int off;
int stopflg;
int wordcnt;
off = -1;
stopflg = 0;
wordcnt = 0;
prev = 0;
for (chr = *input++; ! stopflg; prev = chr, chr = *input++) {
// we've hit the end of the buffer
stopflg = (chr == 0);
// convert whitespace characters to EOS [similar to what strtok might
// do]
switch (chr) {
case ' ':
case '\t':
case '\n':
case '\r':
chr = 0;
break;
}
++off;
// reset on mismatch
// NOTE: we _do_ compare EOS chars here
if (str[off] != chr) {
off = -1;
continue;
}
// we just matched
// if we're starting the word we must ensure we're not in the middle
// of one
if ((off == 0) && (prev != 0)) {
off = -1;
continue;
}
// at the end of a word -- got a match
if (chr == 0) {
++wordcnt;
off = -1;
continue;
}
}
return wordcnt;
}
void
tryout(int expcnt,char *buf)
{
int actcnt;
actcnt = word(buf,"to");
printf("%d/%d -- '%s'\n",expcnt,actcnt,buf);
}
// main -- main program
int
main(int argc,char **argv)
{
char *cp;
--argc;
++argv;
for (; argc > 0; --argc, ++argv) {
cp = *argv;
if (*cp != '-')
break;
switch (cp[1]) {
default:
break;
}
}
tryout(1,"to");
tryout(2,"to to");
tryout(1," to ");
tryout(1,"todo to");
tryout(2,"todo to to");
tryout(2,"doto to to");
tryout(1,"doto to doto");
tryout(0,"doto");
return 0;
}
If you must use only "basic" C functions the above solutions seems ok, but in the case you want to build a more scalable application (and you want to solve the problem in a smarter way) you can use a library that manipulate regular expressions. You can check this answer: Regular expressions in C: examples?
Regexes has the advantage that you can make the regex case unsensible (That is one of your issues).
I usually use pcre because it has the regex style of perl and java.
Here it is a very useful example that uses pcre: http://www.mitchr.me/SS/exampleCode/AUPG/pcre_example.c.html
Let's posit these rules:
"to" can be a word only when there is no char before and after it except the space char
If you accept those rules as valid and correct you need to check 4 conditions:
if (str[i]=='t'&& str[i+1]=='o'&& str[i-1]!='a-z'&& str[i+2]!='a-z'){
word++;
}
Two more conditions can be included to check for the upper case letters.
public class FindCountOfWordInString {
public static void main(String[] args) {
String str = "yhing ghingu jhhtring inghfg ajklingingd me";
String find = "ing";
int count = findCountOfWordInString(str, find);
System.out.println(count);
}
private static int findCountOfWordInString(String str, String find) {
String[] strArr = str.split(" ");
int count = 0, k = 0;
for (int i = 0; i < strArr.length; i++) {
if (strArr[i].contains(find)) {
String strCheck = strArr[i];
char[] findCharArr = find.toCharArray();
for (int j = 0; j < strCheck.length(); j++) {
if (strCheck.charAt(j) == findCharArr[k]) {
k++;
if (k == 3) {
count++;
k = 0;
}
} else {
k = 0;
}
}
}
}
return count;
}
}

Resources