i'm new in c programming and i need some help with this function because i cant figure it out,
i need to make a function that receives a string and prints out the similar words (the order of the letters ,the amount of the letters and if the letters are capital or small doesn't matter) for example:
if received "Nanny have you any cheap peach?"
the output is:
Nanny any
cheap peach
i can't use pointers ,and cant use string.h library.
i tried and came up with this but i had no luck on figuring it out
void FindSimilarWords(char str2[]){
int f,i,j,last,count=0,count1=0,k,letter,temp=0;
char word1[wordsize],word2[wordsize];
for (i = SIZE2 - 1; i >= 0; i--)
{
if (str2[i] != ' ' && str2[i] != '\0')
{
last = i;
break;
}
}
for (i = 0; i<= last; i++)
{
k = 0;
j = i;
do {
word1[k] = str2[j];
k++;
j++;
} while (str2[j] != ' '&&str2[j] != '\0');
word1[k] = '\0';
for (letter =last; letter >= j-1; letter--)
{
temp = letter;
while (temp != ' ')
{
count1++;
temp--;
}
f = 0;
for (k--; k >= 0; k--)
{
if (str2[j] == word1[k])
{
count++;
word2[f] = str2[j];
f++;
}
}
if (count == count1)
printf("%s %s\n", word1, word2);
else
while (letter != ' ')
letter--;
}
while (str2[i] != ' ')
i++;
}
}
Related
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
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
I am looking for a way to change words in string.
I want to change word to another word which have more symbols than first word.
First I count the symbols of the word which i want to change with another one,
than I count how many this word is in the text which is in my program as a char array(string) and now i want to change this word with the word which has more symbols.
There is the code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
Start:
printf("This program can change word or symbols combanation in text\n\n");
char text[550] = "There was a grocery shop in a town. Plenty of mice lived in that grocery shop.\nFood was in plenty for them. hey also wasted the bread\nbiscuits and fruits of the shop.\nThe grocer got really worried. So, he thought I should buy a cat\nand let it stay at the grocery. Only then I can save my things.\nHe bought a nice, big fat cat and let him stay there. The cat had a nice\nime hunting the mice and killing them.\nThe mice could not move freely now. They were afraid that\n\n";
printf("%s\n", text);
int symbols_in_text = 0;
for (int f = 0;f < 550;f++)
{
if (text[f])
{
symbols_in_text++;
}
else
{
break;
}
}
printf("Text has %i symbols\n\n", symbols_in_text);
char b[15];
printf("Which word would you like to chenge in text above?\n(Maximum quantity of Symbols is 15)\nType word or some symbol(s)\n--->>");
cin >> b;
int word_symbols=0;
for (int a = 0;a < 15;a++)
{
if (b[a])
{
word_symbols++;
}
else
{
break;
}
}
printf("Word which you have entered has %i symbols\n", word_symbols);
int word_in_text = 0;
for (int i = 0; i < 550 - word_symbols; i++)
{
int found = 1;
for (int j = 0; j < word_symbols; j++)
{
if (b[j] != text[i + j])
{
found = 0;
break;
}
}
if (found && text[i + word_symbols]==' ')
{
word_in_text++;
}
}
printf("Founded %i %s as the word an is Not the some part of the other word\n", word_in_text,b);
if (word_in_text != 0)
{
char input_word[15];
printf("Enter the word which you want to insert for first entered word\nWarning:You have to enter the world which have %i symbols\n--->>", word_symbols);
cin >> input_word;
int in_word_symbols = 0;
for (int a = 0;a < 15;a++)
{
if (input_word[a])
{
in_word_symbols++;
}
else
{
break;
}
}
printf("The word which you have entered has %i symbols\n\n", in_word_symbols);
if (word_symbols == in_word_symbols)
{
for (int i = 0; i < 550 - word_symbols; i++)
{
int found = 1;
for (int j = 0; j < word_symbols; j++)
{
if (b[j] != text[i + j])
{
found = 0;
break;
}
}
if (found != 0 && text[i + word_symbols] == ' ')
{
for (int j = 0; j < in_word_symbols; j++)
{
text[i + j] = input_word[j];
}
}
}
printf("The result is--->>\n%s\n\n//////////////////////////////////////////END OF////////////////////////////////////////\n\n", text);
}
else if (in_word_symbols > word_symbols)
{
int text_char_index = 0;
step1:
for (int count = 0; count < 550 - word_symbols; count++)
{
text_char_index++;
int found = 1;
for (int j = 0; j < word_symbols; j++)
{
if (b[j] != text[count + j])
{
found = 0;
break;
}
if (found != 0 && text[count + word_symbols] == ' ')
{
count = text_char_index-1;
goto index_changing;
insert:
for (int c = 0; c < in_word_symbols; c++)
{
text[count + c] = input_word[c];
}
if (count > 500)
{
goto printing_result;
}
else
{
continue;
}
}
}
}
index_changing:
for (int l = 466; l > text_char_index + word_symbols; --l)
{
text[l] = text[l + 1];
}
goto insert;
printing_result:
printf("The result is--->>\n%s\n\n//////////////////////////////////////////END OF////////////////////////////////////////\n\n", text);
}
}
goto Start;
return 0;
}
If I enter the word was ( - it is word which i want to change in text) and than I enter the word detected (which has more symbols than first entered word - an it is the word which i want to insert in the text in return "was")
Console output is: There detected
And I can't use in this code method or something like that, I can only use if() and for loop.
Can anyone help me to understand how to do it?
First let's get the ground rules straight -- you are not allowed to use string functions/methods in this exercise, you have to write the code out explicity using primarily if statements and loops.
Rather than create a whole separate block of code to deal with the replacement word being larger than the original, just deal with it as part of the original replacement code -- as well as deal with the possibility that the replacement word is smaller. Both require shifting the original text one way or the other based on the difference between the original word and the replacement.
Here is a rework of your code that does the above and makes a number of style changes and bug fixes. It also makes it a pure 'C' program:
#include <stdio.h>
#include <stdbool.h>
int main()
{
printf("This program can change word or character combinations in text.\n\n");
char text[1024] =
"There was a grocery shop in a town. Plenty of mice lived in that grocery shop.\n"
"Food was in plenty for them. They also wasted the bread, biscuits and fruits\n"
"of the shop. The grocer got really worried. So, he thought I should buy a cat\n"
"and let it stay at the grocery. Only then I can save my things. He bought a\n"
"nice, big fat cat and let him stay there. The cat had a nice time hunting mice\n"
"and killing them. The mice could not move freely now. They were afraid that\n";
while (true) {
printf("%s\n", text);
int characters_in_text = 0;
for (int f = 0; text[f] != '\0'; f++) // not allowed to use strlen()
{
characters_in_text++;
}
printf("Text has %i characters.\n\n", characters_in_text);
char word[17];
printf("Which word would you like to change in text above?\n");
printf("(Maximum quantity of characters is %d)\n", (int) sizeof(word) - 2);
printf("Type word or some character(s)\n");
printf("--->> ");
(void) fgets(word, sizeof(word), stdin);
int a, word_characters = 0;
for (a = 0; word[a] != '\n'; a++)
{
word_characters++;
}
word[a] = '\0';
if (word_characters == 0)
{
break; // exit program
}
printf("Word which you have entered has %i characters.\n", word_characters);
int words_in_text = 0;
for (int i = 0; i < characters_in_text - word_characters; i++)
{
bool found = true;
for (int j = 0; j < word_characters; j++)
{
if (word[j] != text[i + j])
{
found = false;
break;
}
}
if (found)
{
char next_letter = text[i + word_characters];
if (next_letter == ' ' || next_letter == '.' || next_letter == ',' || next_letter == '\n' || next_letter == '\0')
{
words_in_text++;
}
}
}
printf("Found %i instance(s) of %s that are not part of another word.\n", words_in_text, word);
char replacement_word[17];
printf("Enter the word which you want to insert for first entered word.\n");
printf("(Maximum quantity of characters is %d)\n", (int) sizeof(replacement_word) - 2);
printf("Type word or some character(s)\n");
printf("--->> ");
(void) fgets(replacement_word, sizeof(replacement_word), stdin);
int replacement_word_characters = 0;
for (a = 0; replacement_word[a] != '\n'; a++)
{
replacement_word_characters++;
}
replacement_word[a] = '\0';
printf("The word which you have entered has %i characters.\n\n", replacement_word_characters);
int text_shift = replacement_word_characters - word_characters;
for (int i = 0; i < characters_in_text - word_characters; i++)
{
bool found = true;
for (int j = 0; j < word_characters; j++)
{
if (word[j] != text[i + j])
{
found = false;
break;
}
}
if (found)
{
char next_letter = text[i + word_characters];
if (next_letter == ' ' || next_letter == '.' || next_letter == ',' || next_letter == '\n' || next_letter == '\0')
{
if (text_shift > 0)
{
for (int k = characters_in_text; k > i + word_characters - 1; k--)
{
text[k + text_shift] = text[k];
}
}
else if (text_shift < 0)
{
for (int k = i + word_characters; k < characters_in_text + 1; k++)
{
text[k + text_shift] = text[k];
}
}
characters_in_text += text_shift;
for (int j = 0; j < replacement_word_characters; j++)
{
text[i + j] = replacement_word[j];
}
}
}
}
}
return 0;
}
You can see how complicated this code gets without library functions -- testing for the possible punctuation that follows a word would be a lot easier with functions like ispunct() in ctype.h
You also computed a number of useful values in your original code but failed to use them appropriately later on in the code.
Yet to do: you've a lot of error checks to add to this code -- what if the replacement makes the text larger than the array that contains it? You check that a word isn't contained in another by testing the character after the word but fail to test the character before the work, e.g. 'other' vs. 'another'.
Before reading this question please note that my question pertains to a school assignment. For this assignment the only function we are allowed to use is malloc(). Everything else must be done without the use of other libraries.
I'm calling a function ft_split_whitespaces. This function takes a string as input and "splits" it into words. Words are separated spaces, tabs and line breaks.
#include <stdio.h>
char **ft_split_whitespaces(char *str);
int main(void)
{
char *str = "what is";
char **test = ft_split_whitespaces(str);
}
With respect to the example above the result at each index should be
test[0] = "what"
test[1] = "is"
test[2] = NULL
However, I am only able to print the results of test[0]. All other indices do not get printed to display. Heres an example of some code that I assume should print the results of my function.
int i = 0;
while(test[i] != NULL)
{
printf("%s", test[i]);
i++;
}
When this portion of code is ran, only test[0] is printed to the output. I've been sitting here trying to debug my code for hours. If anyone has some spare time and doesn't mind looking over my code, I'd appreciate it tremendously. I have a feeling it may be an issue with how I'm using malloc, but I still cant figure it out.
#include <stdlib.h>
#include <stdio.h>
int count_whitespaces(char *str)
{
int space_count;
int i;
space_count = 0;
i = 0;
while(str[i] != '\0')
{
if(str[i] == ' ' || str[i] == 9 || str[i] == '\n')
{
if(str[i+1] != ' ' && str[i+1] != 9 && str[i+1] != '\n')
space_count++;
}
i++;
}
return (space_count);
}
int check_whitespace(char c)
{
if (c == ' ' || c == 9 || c == '\n' || c == '\0')
{
return (1);
}
else
return(0);
}
int count_characters(char *str, int i)
{
int char_count;
char_count = 0;
while(str[i])
{
if(str[i+1] != ' ' && str[i+1] != 9 && str[i+1] != '\n')
char_count++;
else
break;
i++;
}
return (char_count);
}
char **ft_split_whitespaces(char *str)
{
int i;
int j;
int k;
char **word;
int space;
i = 0;
j = 0;
k = 0;
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
while(str[i] != '\0')
{
if (check_whitespace(str[i]) == 1)
i++;
else
{
if((word[j] = malloc(sizeof(char) * (count_characters(str, i) + 1))) == NULL)
return (NULL);
while (check_whitespace(str[i]) == 0)
{
word[j][k] = str[i];
i++;
k++;
}
j++;
}
}
j++;
word[j] = NULL;
j = 0
return word;
}
You forgot to reset k. The outer while loop in ft_split_whitespaces should look like that
while (str[i] != '\0') {
if (check_whitespace(str[i]) == 1){
i++;
}
else {
if ((word[j] =
malloc(sizeof(char) * (count_characters(str, i) + 1))) == NULL){
return (NULL);
}
while (check_whitespace(str[i]) == 0) {
word[j][k] = str[i];
i++;
k++;
}
word[j][k] = '\0';
j++;
k = 0; // reset k
}
}
So I actually figured out what was going wrong with my code as I finished typing this question (thanks stack overflow!). I decided to post it anyways, because I thought it might be a good learning experience for coding newbies such as myself.
This is where my issue was occurring.
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
while(str[i] != '\0')
{
if (check_whitespace(str[i]) == 1)
i++;
else
{
if((word[j] = malloc(sizeof(char) * (count_characters(str, i) + 1))) == NULL)
return (NULL);
while (check_whitespace(str[i]) == 0)
{
word[j][k] = str[i];
i++;
k++;
}
j++;
}
}
I malloc'd my char **word outside of the while loop using the following code
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
And then within the actual while loop I malloc'd it again using
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
Using malloc multiple times on the same variable was causing all sorts of weird issues. So within the while loop I ended up using a new variable I declared as char *words. Here is that portion of the while loop with the correct code.
word = (char**)malloc(sizeof(char*)*(count_whitespaces(str) + 2));
while(str[i] != '\0')
{
if (check_whitespace(str[i]) == 1)
i++;
else
{
words = malloc(sizeof(char) * (count_characters(str, i) + 1));
k = 0;
while (check_whitespace(str[i]) == 0)
{
words[k] = str[i];
i++;
k++;
}
words[k] = '\0';
word[j] = words;
j++;
}
}
I am trying to write program, which take text and seperate it into sentences.
Input:
Hi, my name is John.
Output:
Hi,
my
name
is
John.
Code
int main ()
{
int str[200];
int i = 0;
puts ("Enter text. Do not forget to put dot at the end.");
do {
str[i] = getchar();
i++;
} while (str[i-1] != '.');
printf("\n");
int k, lenght = 0; //lenght -- the lenght of single word
for (i=0; str[i] != '.'; i++) {
if (str[i] == ' ' || str[i] == '.') {
printf ("\n");
k = i - lenght;
do {
putchar (str[k]);
k++;
} while (str[k] != ' ');
lenght = 0;
}
lenght++;
}
printf ("\n stop");
return 0;
}
If you try to run or if you can see, there is an error. It does not output last word.
I tried to put there this cycle:
do {
if (str[i] == ' ') {
printf("\n");
k=i-lenght;
do {
putchar(str[k]);
k++;
}while(str[k] != ' ');
lenght=0;
}
lenght++;
i++;
}while(str[i+1] != '.');
But its the same cycle... I also tried to make function:
void word (char *c,int index, int lenght ) {
printf ("\n");
int i = index - lenght;
do {
putchar (c[i]);
i++;
} while (c[i] != ' ');
return;
}
and I called it instead of do-while cycle (in the "if section " of the code):
for (i=0; str[i] != '.'; i++) {
if (str[i] == ' ' || str[i] == '.') {
word(str, i, lenght);
lenght = 0;
}
lenght++;
}
What surpriced me was, that the function was "outputting" only the firs Word in sentence. If the first word was "John" it output "John" "ohn" "hn".
So there is not just one question...
How to remake/repaire the cycle/function to output what I want - all of the words in the sentence?
Why it does not work? Well I know the answer - beacouse thy cycle is built to end on character ' ', but not the '.', but when I tried to change it, it output one more random character after dot.
Just please dont blame me for the code, I am just begginer trying to learn something. I know its not a Masterpiece and I can and I will make it shorter before I finish it.
The reason it doesn't print the last word is that, as soon as it reads it and finds the '.', the for-loop terminates so it doesn't process and output that word.
You could change the for-loop condition to look for the terminating '\0' instead, that should fix it.
#include<stdio.h>
int main ()
{
char str[200];
int i = 0;
puts ("Enter text:");
gets(str);
int k, length = 0;
printf("So the words are:\n");
while(str[i]!='\0')
{
if (str[i] == ' ') {
k = i - length;
do {
putchar (str[k]);
k++;
} while (str[k] != ' ');
printf ("\n");
length = (-1);
}
else if (str[i+1] == '\0') {
k = i - length;
do {
putchar (str[k]);
k++;
} while (str[k] != '\0');
length = 0;
}
length++;
i++;
}
return 0;
}