Erase blank spaces between string in C - 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.

Related

Counting words in string with c

the push to vaccinate children has taken on fresh urgency amid concerns that the new omicron variant of the virus first identified in southern africa and hong kong in late november will spread quickly in the united states causing a surge in infections already back on the rise from the easily transmitted delta variant given the pervasiveness of delta and prospects of new variants spreading in the united states having as much immunity in the population as possible is critical said dr amesh adalja senior scholar at the johns hopkins center for health security
This is my assignment:
replace multiple spaces to one space between words and delete unnecessary spaces at the beginning and the end.
count the words
print edited string
dont use a new string, just edit.
I can't find problem. It should count the words but it can not do. Help me, please.
//Counting words program C
#include <stdio.h>
#define N 5000
int main(void) {
FILE *fp;
char text[N];
int k, d, leng, spacecount = 0;
int m, j, z, i, p, n;
if ((fp = fopen("soru.txt", "r")) == NULL) {
printf("Dosya acma hatasi!");
return 1;
}
fgets(text, N - 1, fp);
while (k < N && text[k] != '\0') {
leng++;
k++;
}
z = leng;
for (i = 0; i < leng; i++) {
if (i = 0 && text[i] == ' ') {
z--;
for (m = 0; m < leng; m++) {
text[m] = text[m + 1];
}
i--;
text[z] == '\0';
} else
if (text[i] ==' ' && text[i + 1] == ' ') {
z--;
for (j = i; j < leng; j++) {
text[j + 1] = text[j + 2];
}
i--;
text[z] == '\0';
} else
if (text[i] == ' ' && text[i + 1] == '\0') {
z--;
for (j = i; j < leng; j++) {
text[j] = text[j + 1];
}
i--;
text[z] == '\0';
} else
if (text[i] == '\0') {
break;
}
}
while (text[d] != '\0') {
if (text[d] == ' ')
spacecount++;
d++;
}
printf("kelime sayisi: %d" , spacecount + 1);
printf("\n cikti:%s ", text);
fclose(fp);
return 0;
}
I can't find problem. It should count the word but it can not do. Help me, please
for(i=0; i < leng; i++) {
if(i=0 && text[i]== ' '){
z--;
for(m=0; m< leng; m++ ){
text[m] = text [m+1];}
i--;
}
else if(1<i<z && text[i] ==' ' && text[i+1] == ' ' ){
z--;
for(j=i; j<leng ; j++) {
text[j+1] = text [j+2];}
i--;
}
else if(i=z && text[i] ==' ' && text[i+1] == '\0' ){
z--;
for(j=i; j<leng ; j++) {
text[j] = text [j+1]; }
i--;
}
},// I think problem in here. Endless loop
Your code is too complicated. You can solve the problem with 2 index variables: one to read the characters from the input line, one to write the relevant characters into the same buffer.
You would keep track of the previous character, starting with space, and detect the beginning of words as the current character is not a space following a space. You would thus count the words and only output a space before each word except the first on a line.
Here is a modified version:
//Counting words program C
#include <stdio.h>
#define N 5000
int main(void) {
FILE *fp;
char text[N];
int total_words = 0;
if ((fp = fopen("soru.txt", "r")) == NULL) {
printf("Dosya açma hatası!\n");
return 1;
}
while (fgets(text, N, fp) != NULL) {
int len = strlen(text);
int word_count = 0;
char c, lastc = ' ';
int i, j;
// strip the trailing newline
if (len > 0 && text[len - 1] == '\n') {
text[--len] == '\0';
}
for (i = j = 0; i < len; i++) {
c = text[i];
if (c != ' ') {
if (lastc == ' ') {
if (word_count > 0) {
// output a space between words
text[j++] = ' ';
}
word_count++;
}
text[j++] = c; // copy the non space character
}
lastc = c;
}
text[j] = '\0'; // set the null terminator
printf("kelime sayısı: %d\n", word_count);
printf("çıktı: %s\n", text);
total_words += word_count;
}
fclose(fp);
printf("\ntoplam kelime sayısı: %d\n", total_words);
return 0;
}
Note a silly bug in your code: if (i = 0 && text[i] == ' ') is parsed as if ((i = (0 && (text[i] == ' '))) != 0) which is always false and sets i to the value 0. C expression syntax is very powerful but somewhat error prone and confusing. I advise you to use -Wall or -Weverything as a compiler option to let the compiler warn about potential mistakes.
Similarly, you should not write if (1<i<z && ...: 1<i<z is parsed as 1<(i<z) which is always false. You must write 1 < i && i < z or more idiomatically i > 1 && i < z

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

Folding input lines every nth column (K&R 1-22) in C

Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column.
The algorithm I decided to follow for this was as follows:
If length of input line < maxcol (the column after which one would have to fold), then print the line as it is.
If not, from maxcol, I check towards it's left, and it's right to find the closest non-space character, and save them as 'first' and 'last'. I then print the character array from line[0] to line[first] and then the rest of the array, from line[last] to line[len] becomes the new line array.
Here's my code:
#include <stdio.h>
#define MAXCOL 5
int getline1(char line[]);
int main()
{
char line[1000];
int len, i, j, first, last;
len = getline1(line);
while (len > 0) {
if (len < MAXCOL) {
printf("%s\n", line);
break;
}
else {
for (i = MAXCOL - 1; i >= 0; i--) {
if (line[i] != ' ') {
first = i;
break;
}
}
for (j = MAXCOL - 1; j <= len; j++) {
if (line[j] != ' ') {
last = j;
break;
}
}
//printf("first %d last %d\n", first, last);
for (i = 0; i <= first; i++)
putchar(line[i]);
putchar('\n');
for (i = 0; i < len - last; i++) {
line[i] = line[last + i];
}
len -= last;
first = last = 0;
}
}
return 0;
}
int getline1(char line[])
{
int c, i = 0;
while ((c = getchar()) != EOF && c != '\n')
line[i++] = c;
if (c == '\n')
line[i++] = '\n';
line[i] = '\0';
return i;
}
Here are the problems:
It does not do something intelligent with very long lines (this is fine, as I can add it as an edge case).
It does not do anything for tabs.
I cannot understand a part of the output.
For example, with the input:
asd de def deffff
I get the output:
asd
de
def
defff //Expected until here
//Unexpected lines below
ff
fff
deffff
deffff
deffff
Question 1 - Why do the unexpected lines print? How do I make my program/algorithm better?
Eventually, after spending quite some time with this question, I gave up and decided to check the clc-wiki for solutions. Every program here did NOT work, save one (The others didn't work because they did not cover certain edge cases). The one that worked was the largest one, and it did not make any sense to me. It did not have any comments, and neither could I properly understand the variable names, and what they represented. But it was the ONLY program in the wiki that worked.
#include <stdio.h>
#define YES 1
#define NO 0
int main(void)
{
int TCOL = 8, ch, co[3], i, COL = 19, tabs[COL - 1];
char bls[COL - 1], bonly = YES;
co[0] = co[1] = co[2] = 0;
while ((ch = getchar()) != EOF)
{
if (ch != '\t') {
++co[0];
++co[2];
}
else {
co[0] = co[0] + (TCOL * (1 + (co[2] / TCOL)) - co[2]);
i = co[2];
co[2] = TCOL + (co[2] / TCOL) * TCOL;
}
if (ch != '\n' && ch != ' ' && ch != '\t')
{
if (co[0] >= COL) {
putchar('\n');
co[0] = 1;
co[1] = 0;
}
else
for (i = co[1]; co[1] > 0; --co[1])
{
if (bls[i - co[1]] == ' ')
putchar(bls[i - co[1]]);
else
for (; tabs[i - co[1]] != 0;)
if (tabs[i - co[1]] > 0) {
putchar(' ');
--tabs[i - co[1]];
}
else {
tabs[i - co[1]] = 0;
putchar(bls[i - co[1]]);
}
}
putchar(ch);
if (bonly == YES)
bonly = NO;
}
else if (ch != '\n')
{
if (co[0] >= COL)
{
if (bonly == NO) {
putchar('\n');
bonly = YES;
}
co[0] = co[1] = 0;
}
else if (bonly == NO) {
bls[co[1]] = ch;
if (ch == '\t') {
if (TCOL * (1 + ((co[0] - (co[2] - i)) / TCOL)) -
(co[0] - (co[2] - i)) == co[2] - i)
tabs[co[1]] = -1;
else
tabs[co[1]] = co[2] - i;
}
++co[1];
}
else
co[0] = co[1] = 0;
}
else {
putchar(ch);
if (bonly == NO)
bonly = YES;
co[0] = co[1] = co[2] = 0;
}
}
return 0;
}
Question 2 - Can you help me make sense of this code and how it works?
It fixes all the problems with my solution, and also works by reading character to character, and therefore seems more efficient.
Question 1 - Why do the unexpected lines print? How do I make my program/algorithm better?
You are getting the unexpected lines in the output because after printing the array, you are not terminating the new line array with null character \0 -
Here you are copying character from starting from last till len - last, creating a new line array:
for (i = 0; i < len - last; i++) {
line[i] = line[last + i];
}
You have copied the characters but the null terminating character is still at its original position. Assume the input string is:
asd de def deffff
So, initially the content of line array will be:
"asd de def deffff\n"
^
|
null character is here
Now after printing asd, you are copying characters from last index of line till len - last index to line array itself starting from 0 index. So, after copying the content of line array will be:
"de def deffff\n deffff\n"
|____ _____|
\/
This is causing the unexpected output
(null character is still at the previous location)
So, after for loop you should add the null character just after the last character copied, like this:
line [len - last] = '\0';
With this the content of line array that will be processed in the next iteration of while loop will be:
"de def deffff\n"
One more thing, in the line array you can see the \n (newline) character at the end. May you want to remove it before processing the input, you can do:
line[strcspn(line, "\n")] = 0;
Improvements that you can do in your program:
1. One very obvious improvement that you can do is to use pointer to the input string while processing it. With the help of pointer you don't need to copy the rest of the array, apart from processed part, again to the same array till the program process the whole input. Initialize the pointer to the start of the input string and in every iteration just move the pointer to appropriate location and start processing from that location where pointer is pointing to.
2. Since you are taking the whole input first in a buffer and then processing it. You may consider fgets() for taking input. It will give better control over the input from user.
3. Add a check for line array overflow, in case of very long input. With fgets() you can specify the maximum number of character to be copied to line array from input stream.
Question 2 - Can you help me make sense of this code and how it works?
The program is very simple, try to understand it at least once by yourself. Either use a debugger or take a pen and paper, dry run it once for small size input and check the output. Increase the input size and add some variations like multiple space characters and check the program code path and output. This way you can understand it very easily.
Here's another (and I think better) solution to this exercise :
#include <stdio.h>
#define MAXCOL 10
void my_flush(char buf[]);
int main()
{
int c, prev_char, i, j, ctr, spaceleft, first_non_space_buf;
char buf[MAXCOL+2];
prev_char = -1;
i = first_non_space_buf = ctr = 0;
spaceleft = MAXCOL;
printf("Just keep typing once the output has been printed");
while ((c = getchar()) != EOF) {
if (buf[0] == '\n') {
i = 0;
my_flush(buf);
}
//printf("Prev char = %c and Current char = %c and i = %d and fnsb = %d and spaceleft = %d and j = %d and buf = %s \n", prev_char, c, i, first_non_space_buf, spaceleft, j, buf);
if ((((prev_char != ' ') && (prev_char != '\t') && (prev_char != '\n')) &&
((c == ' ') || (c == '\t') || (c == '\n'))) ||
(i == MAXCOL)) {
if (i <= spaceleft) {
printf("%s", buf);
spaceleft -= i;
}
else {
putchar('\n');
spaceleft = MAXCOL;
for (j = first_non_space_buf; buf[j] != '\0'; ++j) {
putchar(buf[j]);
++ctr;
}
spaceleft -= ctr;
}
i = 0;
my_flush(buf);
buf[i++] = c;
first_non_space_buf = j = ctr = 0;
}
else {
if (((prev_char == ' ') || (prev_char == '\t') || (prev_char == '\n')) &&
((c != ' ') && (c != '\t') && (c != '\n'))) {
first_non_space_buf = i;
}
buf[i++] = c;
buf[i] = '\0';
}
prev_char = c;
}
printf("%s", buf);
return 0;
}
void my_flush(char buf[])
{
int i;
for (i = 0; i < MAXCOL; ++i)
buf[i] = '\0';
}
Below is my solution, I know the thread is no longer active but my code might help someone who's facing issues to grasp the already presented code snippets.
*EDIT
explaination
Keep reading input unless the input contains '\n', '\t' or there've been
atleast MAXCOl chars.
Incase of '\t', use expandTab to replace with required spaces and use printLine if it doesn't exceed MAXCOl.
Incase of '\n', directly use printLine and reset the index.
If index is 10:
find the last blank using findBlank ad get a new index.
use printLine to print the current line.
get new index as 0 or index of newly copied char array using the newIndex function.
code
/* fold long lines after last non-blank char */
#include <stdio.h>
#define MAXCOL 10 /* maximum column of input */
#define TABSIZE 8 /* tab size */
char line[MAXCOL]; /* input line */
int expandTab(int index);
int findBlank(int index);
int newIndex(int index);
void printLine(int index);
void main() {
int c, index;
index = 0;
while((c = getchar()) != EOF) {
line[index] = c; /* store current char */
if (c == '\t')
index = expandTab(index);
else if (c == '\n') {
printLine(index); /* print current input line */
index = 0;
} else if (++index == MAXCOL) {
index = findBlank(index);
printLine(index);
index = newIndex(index);
}
}
}
/* expand tab into blanks */
int expandTab(int index) {
line[index] = ' '; /* tab is atleast one blank */
for (++index; index < MAXCOL && index % TABSIZE != 0; ++index)
line[index] = ' ';
if (index > MAXCOL)
return index;
else {
printLine(index);
return 0;
}
}
/* find last blank position */
int findBlank(int index) {
while( index > 0 && line[index] != ' ')
--index;
if (index == 0)
return MAXCOL;
else
return index - 1;
}
/* re-arrange line with new position */
int newIndex(int index) {
int i, j;
if (index <= 0 || index >= MAXCOL)
return 0;
else {
i = 0;
for (j = index; j < MAXCOL; ++j) {
line[i] = line[j];
++i;
}
return i;
}
}
/* print line until passed index */
void printLine(int index) {
int i;
for(i = 0; i < index; ++i)
putchar(line[i]);
if (index > 0)
putchar('\n');
}

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"

Counting the vowels and characters in each word of a sentence

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.

Resources