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;
}
Related
In this code I have got a string input- "WUBABCWUBNAWBWUB".
here i need to remove the word "WUB" and print the remaining.Example: "ABC NAWB";
i have almost solved it but the problem is when i give the input(given above) I get a garbage value at the end.It shows: "ABC NAWB~#".I cant understand whats wrong with the code,please help me to remove those garbage values.
#include <stdio.h>
#include <string.h>
int main() {
char str[201], original[201];
int cnt = 0, i, j = 0;
int len = strlen(str);
gets(str);
for(i = 0; i < len-3; i++) {
if(str[i] == 'W' && str[i+1] == 'U' && str[i+2] == 'B' && i != len) {
if(i != 0 && i != len-3) {
original[cnt] = ' '; //here i changed "WUB" into a blank line
j++;
cnt++;
}
i = i+2;
} else {
original[j] = str[i];
cnt++;
j++;
}
}
printf("%c %c\n", original[j], original[j+1]);
printf("%s", original);
printf("\n\nj=%d,i=%d,cnt=%d", j, i, cnt);
}
A few modifications:
I have added a '\0' the end at the new string
I have modified the code such that it works even if the end is not equal to WUB (maybe useless modification)
I have removed the redundant j index
I have replaced the gets function with the more secure fgets
#include<stdio.h>
#include<string.h>
int main()
{
char str[201],original[201];
fgets(str, 200, stdin);
int cnt=0,i, len=strlen(str);
for(i = 0; i <= len-3; i++) {
if(str[i]=='W' && str[i+1]=='U' && str[i+2]=='B' && i!=len) {
if(i!=0 && i!=len-3) {
original[cnt++] = ' '; //here i changed "WUB" into a blank line
}
i = i+2; // to jump over the "WUB" word
} else {
original[cnt++] = str[i];
}
}
for (int j = i; j < len; j++) { // to deal with the case the string doesn't terminate with "WUB"
original[cnt++] = str[j];
}
original[cnt++] = '\0';
//printf("%c %c\n",original[cnt],original[cnt+1]);
printf("%s",original);
//printf("\n\n,i=%d,cnt=%d",i,cnt);
}
Strings are actually a one-dimensional array of characters terminated by a null character '\0'. so in your program original is a character array and once the values are assigned to it, at last '\0' should be there so adding just one line of code may help you get correct output.
original[j]='\0';
thanks guys,i've solved the problem.The problem was solved after giving
original[j]='/0';
after the loop.I also used the cnt integer to avoid blanks more than once.Here is my new code.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str[201],original[201];
fgets(str,201,stdin);
int cnt=0,i,j=0,len=strlen(str);
for(i=0;str[i]!='\0';i++){
if(str[i]=='W' && str[i+1]=='U' && str[i+2]=='B')
{
if(i!=0 && i!=len-3&&cnt==0&&j!=0)
{
original[j] = ' ';
cnt++;
j++;
}
i=i+2;
}
else
{
original[j] = str[i];
cnt=0;
j++;
}
}
original[j]='\0';
printf("%s",original);
}
I'm trying to write a program that does Run-Length-Encoding. I wrote the program but I want to cancel the entire loop when there is a non-alphabet character in input. I mean, it should give an output like "The input is not valid!".
I tried several if conditions but every time it encodes the alphabet characters till the non-alphabet character, and then skip that character and continue to encode. Where and how should I put the if statement?
int main() {
int i, txtLen=0, count;
char text[100];
printf("Please enter a text to RLE:\n");
scanf("%s", text);
while (text[i] != '\0') {
txtLen++;
i++;
}
for (i=0; i<txtLen; i++) {
printf("%c", text[i]);
count = 1;
while (text[i+1] == text[i]){
count++;
i++;
}
if (count != 1) {
printf("%d", count);
}
}
return 0;
}
When I tried to put if statements, the input and output were like that:
Input: aa?aaabbb
Output: a2a3b3
Please do not give any suggestions or comments for other parts of my code.
int main(void) {
int i, txtLen=0, count;
char text[100];
printf("Please enter a text to RLE:\n");
scanf("%s", text);
while (text[i] != '\0') {
// check if the value of each char if it is within the alphabetical range of char
if((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z')) {
printf("False Format\n");
break;
}
txtLen++;
i++;
}
for (i=0; i<txtLen; i++) {
printf("%c", text[i]);
count = 1;
while (text[i+1] == text[i]){
count++;
i++;
}
if (count != 1) {
printf("%d", count);
}
}
return 0;
}
I tried modifying this code to print
no solution
if there is no input by user. That is, if I run the program and simply press enter it should print no solution. I added the code that's meant to do that to check if the string length is 0 then print but it doesn't work
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i, j, ctr;
fgets(str1, sizeof str1, stdin);
j = 0; ctr = 0;
if (strlen(str1) == 0) {
printf_s("no solution");
}
else
for (i = 0; i <= (strlen(str1)); i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if (str1[i] == ' ' || str1[i] == '\0')
{
newString[ctr][j] = '\0';
ctr++; //for next word
j = 0; //for next word, init index to 0
}
else if (str1[i] == '.' || str1[i] == ',')
{
newString[ctr][j] = '\0';
ctr--; //for next word
j = - 1;
}
else
{
newString[ctr][j] = str1[i];
j++;
}
}
printf("\n\n");
for (i = 0; i < ctr; i++)
printf(" %s\n", newString[i]);
return 0;
}
fgets() will add a new line to your string (see this link for more information) which means when you simply press enter your string length(since your string includes \n) is 1 , you should say:
if (strlen(str1) == 1) {
printf_s("no solution");
// it's better to add a return 0; here if you don't want to continue the program
}
or use this instead:
if (!strcmp(str1,"\n")) {
printf_s("no solution");
}
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++;
}
}
I wrote a code that counts how many words are there in a sentence, but it does not work in cases like this for example:
"hello world."
It needs to return that there are 2 words, but it returns 4 because of the spaces. It's only good for the case of one space between each word. This is my code:
int counthowmanywordsinasentence(char sentence[])// help forfunc7
{
int count = 0, i;
for (i = 0;sentence[i] != '\0';i++)
{
if (sentence[i] == ' ')
count++;
}
return (count+1);
}
Use a flag. If you encounter a space & flag is not set, set the flag and increment count. If space is encountered & flag is set , just ignore that case. And if flag is set & char(i.e. sentence[i]) is not space, reset flag.
This is the simplest of all answers, just add 2 lines
#include <stdio.h>
int counthowmanywordsinasentence(char sentence[])// help forfunc7
{
int count = 0, i;
for (i = 0;sentence[i] != '\0';i++)
{
if (sentence[i] == ' ')
count++;
while (sentence[i] == ' ')
i++;
}
return (count+1);
}
You can safely replace your if by this new version:
if (sentence[i] == ' ' && sentence[i+1] != ' ')
Which means you will be only counting the last space in each space sequence. So in your case of 4 contiguous spaces, you will count only the last one.
You will still need to decide what to do in these two cases:
" hello world."
"hello world "
As you need to know if these should count as 2 or 3 words in both cases.
So sscanf already does what you need it will eat any number of whitespaces before a string including tabs. This algorithm is safe with leading or trailing spaces.
int countHowManyWordsInASentence(char* sentence){
int result = 0;
int i = 0;
while(sscanf(sentence, "%*s%n", &i) != EOF){
sentence += i;
result++;
}
return result;
}
sscanf is extremely versatile you can easily read out each word as follows:
int countHowManyWordsInASentence(char* sentence){
int result = 0;
int size = strlen(sentence);
if(size > 0){
char* word = (char*)malloc((size + 1) * sizeof(char));
for(int i = 0; sscanf(sentence, "%s%n", word, &i) > 0; sentence += i){
result++;
}
free(word);
}
return result;
}
int counthowmanywordsinasentence(char sentence[])
{
int count = 0, i;
char ch, pre = ' ';
for (i = 0; (ch=sentence[i]) != '\0'; i++, pre = ch)
{
if (pre == ' ' && ch != ' ')//reckon the rise
count++;
}
return count;
}
You'll have to decide what is a word first :) let's assume a word is any sequence of characters with at least one alphabetic character (A-Za-z). then you can follow #Abhilash's suggestion to complete your code.
int wordcount(char *sentence) {
int count = 0;
int is_word = 0;
int i;
for(i=0; sentence[i]!='\0'; i++) {
if(isalpha(sentence[i])) {
is_word = 1;
}
if(sentence[i] == ' ' && is_word) {
count++;
is_word = 0;
}
}
return count + is_word;
}