How to pick a word in a text line in C - c

How to pick a word in a text line in string in C language?
Example string "My mother cooks well...." How I can edit only "cooks" in that string? Question is for an exam. How can I find lenght and how can I edit second word in text, for example?
#include <stdio.h>
int length(char* s) // Lenght
{
int d = -1;
while (s[++d]);
return d;
}
int main() //main function
{
char str[101], c;
int i = 0;
printf("Entry text:\n");
scanf("%s", str); //Input text line
printf("First word lenght('%s') je %d.\n", str, lenght(str));
do
{
scanf("%c", &c);
str[i++] = c;
} while (c != '\n');
str[i - 1] = 0;
printf("The rest: '%s'\n", str); //Rest lenght
printf("The rest lenght: %d.", lenght(str));
return 0;
}

You can use strtok()
int i = 0;
char delim[2] = " ";
char *c = strtok(str, delim); //space is the delimiter.
// c points to the first word
while(c != NULL)
{
printf(" %s\n",c);
c = strtok(str, NULL) //notice this NULL
i++;
if(i == 2)
{
//edit your 2nd word
//break if you want after this or carry on
}
}

See strstr(3). I think that's all you need.

Related

how to remove a character from a string with loop?

Im trying to make the program remove a character from a string that the user is putting in but i get an error inside the loop. (side question: is adding a character inside the string the "same" code with some small changes?)
PS New to programming...
Is this what you are trying to achieve?
Changes:
getchar() and fgets() to scanf()
added strlen() to get length of string
added lenght of input string to printf
added zero init of strings
Note: After each input with scanf() you have to press enter.
int main()
{
char str[100] = { 0 };
char ch[5] = { 0 };
int k, j;
printf("Write text:\n");
scanf("%s", str);
printf("Input was: %s\nLength: %d\n", str, strlen(str));
printf("Write a character that should be removed\n");
scanf("%s", ch);
for (k = 0, j = 0; k < strlen(str); k++)
{
if (str[k] != ch[0]) {
str[j] = str[k];
j++;
}
}
str[j] = '\0';
printf("String after removing a character: %s", str);
}
Problems with your code:
str[k] != ch would be a valid test if ch were indeed a character and not an array of characters of length 5. This is going to compare the character value of str[k] with the address &ch[0].
k < str would be a valid comparison if k was a char * pointer that was initialized at &str[0], not an int loop index starting at 0.
Corrected code:
int main(void)
{
char str[100];
char ch[5];
int k, j;
printf("Write text:\n");
//getchar();
fgets(str, 100, stdin);
printf("Input was: %s\n", str);
printf("Write a character that should be removed\n");
//getchar();
fgets(ch, 5, stdin);
for (k = 0, j = 0; k < strlen(str); k++)
{
if (str[k] != ch[0])
{
str[j] = str[k];
j++;
}
}
str[j] = '\0';
printf("String after removing a character = %s", str);
return 0;
}
Here you have two implementations. Both remove all occurrences of the char ch from the string str
First algorithm is much faster. The second slower but easy to understand
#include <stdio.h>
#include <string.h>
char *removechar(char *str, int ch)
{
char *cptr = str, *readptr = str;
while(*readptr)
{
if(*readptr == ch)
{
readptr++;
}
else
{
*cptr++ = *readptr++;
}
}
*cptr = 0;
return str;
}
char *removechar(char *str, int ch)
{
char *cpos = str;
while((cpos = strchr(cpos, ch)))
{
strcpy(cpos, cpos + 1);
}
return str;
}
int main()
{
char s[] = "Hello World";
printf("%s\n", removechar(s, 'd'));
printf("%s\n", removechar(s, 'l'));
return 0;
}
Is this what you want to achieve?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char str[100],c;
printf("Write text:\n");
fgets(str,100,stdin);
printf("Input was: %s\n", str);
printf("Write a character that should be removed\n");
c=getchar();
for(int k=0;k<strlen(str);k++){
if(str[k]==c){
for(int j=k;j<strlen(str);j++){
str[j]=str[j+1];
}
}
}
printf("String after removing a character = %s", str);
return 0;
}

Hi, I tried to make this program run multiple times(using for(;;) and do...while) but every time it stops at reading the string

I created this program to read a string from the user and to sort it's word alphabetically, finally I tried to add a funtion for helping me running this program as much as the user wants, but never works. I used do...while, but every time the program stops before reading the string.
char *words[L];
char *word;
char sentence[100];
int i = 0, nrCuvinte = 0;
int j, k, ok, n, lung;
for(j=0;j<L;++j)
{
words[j] = (char*)malloc(L*sizeof(char));
}
printf("Enter any sentence you want: \n");
fgets(sentence,99,stdin);
lung = strlen(sentence);
if(sentence[lung-1] == '\n')
{
sentence[lung-1] = '\0';
}
printf("\n");
word = strtok(sentence, " .,-;/?!");
for(j=0;j<(strlen(word)+1);j++)
{
word[j] = tolower((unsigned char) word[j]);
}
while(word != NULL)
{
for(j=0;j<(strlen(word)+1);j++)
{
word[j] = tolower((unsigned char) word[j]);
}
strcpy(words[i],word);
word = strtok(NULL, " .,-;/?!");
++i;
++nrCuvinte;
}
n = nrCuvinte-1;
do{
ok =1;
for(k=0;k<n;++k)
{
if(strcmp(words[k],words[k+1])>0)
{
char *aux;
aux = words[k];
words[k] = words[k+1];
words[k+1]= aux;
ok = 0;
}
}
--n;
}while(n>0&&(ok==0));
for(j=0;j<nrCuvinte;++j)
{
puts(words[j]);
}
for(j=0;j<L;++j)
{
free(words[j]);
words[j]=0;
}
I added the #includes, a #define for L, wrapped everything inside a main function and placed a while(1) loop inside the main function. At the start of the while(1) loop I added nrCuvinte = 0; and i = 0; in order to reset those variables. I also added the ability to break out of the while(1) loop by typing in 'yes' when asked to do so.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define L 500
int main(){
char user_input[4];
char *words[L];
char *word;
char sentence[100];
int i = 0, nrCuvinte = 0;
int j, k, ok, n, lung;
while(1){
i = 0;
nrCuvinte = 0;
for(j=0;j<L;++j){
words[j] = (char*)malloc(L*sizeof(char));
}
printf("Enter any sentence you want: \n");
fgets(sentence,99,stdin);
lung = strlen(sentence);
if(sentence[lung-1] == '\n'){
sentence[lung-1] = '\0';
}
printf("\n");
word = strtok(sentence, " .,-;/?!");
for(j=0;j<(strlen(word)+1);j++){
word[j] = tolower((unsigned char) word[j]);
}
while(word != NULL)
{
for(j=0;j<(strlen(word)+1);j++){
word[j] = tolower((unsigned char) word[j]);
}
strcpy(words[i],word);
word = strtok(NULL, " .,-;/?!");
++i;
++nrCuvinte;
}
n = nrCuvinte-1;
do{
ok =1;
for(k=0;k<n;++k){
if(strcmp(words[k],words[k+1])>0)
{
char *aux;
aux = words[k];
words[k] = words[k+1];
words[k+1]= aux;
ok = 0;
}
}
--n;
}while(n>0&&(ok==0));
for(j=0;j<nrCuvinte;++j){
puts(words[j]);
}
for(j=0;j<L;++j){
free(words[j]);
}
printf("If you want to exit type 'yes', else press enter.\n");
fgets(user_input,4,stdin);
if(strcmp(user_input, "yes") == 0)
break;
}
}
I also wrote another version, this time wrapping your code inside a function and calling this function from the main function inside a while(1) loop:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define L 500
void sort_sentence(){
char *words[L];
char *word;
char sentence[100];
int i = 0, nrCuvinte = 0;
int j, k, ok, n, lung;
for(j=0;j<L;++j)
{
words[j] = (char*)malloc(L*sizeof(char));
}
printf("Enter any sentence you want: \n");
fgets(sentence,99,stdin);
lung = strlen(sentence);
if(sentence[lung-1] == '\n'){
sentence[lung-1] = '\0';
}
printf("\n");
word = strtok(sentence, " .,-;/?!");
for(j=0;j<(strlen(word)+1);j++){
word[j] = tolower((unsigned char) word[j]);
}
while(word != NULL){
for(j=0;j<(strlen(word)+1);j++){
word[j] = tolower((unsigned char) word[j]);
}
strcpy(words[i],word);
word = strtok(NULL, " .,-;/?!");
++i;
++nrCuvinte;
}
n = nrCuvinte-1;
do{
ok =1;
for(k=0;k<n;++k){
if(strcmp(words[k],words[k+1])>0){
char *aux;
aux = words[k];
words[k] = words[k+1];
words[k+1]= aux;
ok = 0;
}
}
--n;
}while(n>0&&(ok==0));
for(j=0;j<nrCuvinte;++j){
puts(words[j]);
}
for(j=0;j<L;++j){
free(words[j]);
}
}
int clean_stdin()
{
while (getchar()!='\n');
return 1;
}
int main(){
int user_input;
char c;
while(1){
sort_sentence();
do{
printf("If you want to exit type '2', if you want to continue type '1'.\n");
}while(((scanf("%d%c", &user_input, &c) != 2 || c!='\n') && clean_stdin()) ||( user_input != 2 && user_input != 1));
if(user_input == 2)
return 0;
}
}
Edit: Now in the second code example the user will be prompted with a message telling her/him to enter 1 or 2 until he/she inputs 1 or 2, every other input results in getting prompted with the same message again. If 1 is entered the next sort_sentence() function call is executed, if 2 is read the program terminates. Credits go to MOHAMED for his elegant solution on the community wiki. I used his idea here.

How to store array in address C

basically we are provided with the main function:
#include <stdio.h>
#include <string.h>
#include <strings.h>
#define STORAGE 255
{
int c;
char s[STORAGE];
for(;;) {
(void) printf("n=%d, s=[%s]\n", c = getword(s), s);
if (c == -1)break;
}}
we are not to change that
and we have to create the function getword() which should contain a loop that reads a characters,
store it in a array in the address provided one by one and it should stop for whitespace (tab, space, eof)
basically i have this:
int getword(char *w)
{
char str[255];
int i = 0;
int charCount = 0;
printf("enter your sentence:\n");
gets(str);
/*this was provided by the professor, but i'm not sure how to use it
while (( iochar - getchar()) !=EOF);
*/
for(i = 0; str[i] != '\0'; i++) //loop that checks tab and spaces
{
if(str[i] != ' ' && str[i] != '\t')
{
charCount++;
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount);
return 0;}
right now the output of the program is:
enter your sentence:
hey stockoverflow
your string: 'hey stockoverflow' contains 16 of letters
n=0, s=[]
so i'm saving the string and counting it, but i'm not storing it where i should be.
it should display n=16, s=[hey stockoverflow]
actually it should display n=3, s=[hey]
any help would be appreciated
This may be what you are looking for:
for(i = 0; str[i] != '\0'; i++) //loop that checks tab and spaces
{
if(str[i] != ' ' && str[i] != '\t')
{
charCount++;
}
else
{
str[i] = '\0'; // Terminate str
break; // Break out of the for-loop
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount);
strcpy(w, str); // Add this line to copy str into w (which is s from main)
return strlen(w); // Return the length of the result string

Deleting letters in a string in C

I've been assigned to construct a code, doing the following:
Ask the user to input a word (30 letters max), and then delete all the "A,a,O,o" letters and print it without any spaces. eg: input: OkleaAo, output: kle
I've been told the easier way is to use 2 arrays, and with an IF loop, to add letters which aren't A/a/o/O to the second array, and then print it.
I'm really stuck now, I know I have to use pointers, but for it isn't working.
Any help, advise?
I wrote something like this:
#include <stdio.h>
char input[30], *p;
char output[30];
main()
{
printf("Enter a string:\n", input);
scanf("%s", input);
if *(p==o);
{
*p=0;
printf("String after deletion:", input);
}
}
#include <stdio.h>
#include <string.h>
int main(){
char input[30+1];
char output[30+1];
int i, j;
printf("Enter a string :");
scanf("%30[^\n]", input);
for(j = i = 0;input[i];++i){
char *p, ch = input[i];
p = strchr("AaOo ", ch);
if(p == NULL)
output[j++] = ch;
}
output[j] = '\0';
printf("\nString after deletion: %s\n", output);
return 0;
}
#include <stdio.h>
int main(){
char input[30+1];
char *in, *out;
printf("Enter a string :");
scanf("%30[^\n]", input);
out = in = input;
while(*in){
char ch = *in;
if(ch != 'A' && ch != 'a' && ch != 'O' && ch != 'o' && ch != ' ')
*out++ = *in;
++in;
}
*out = '\0';
printf("\nString after deletion: %s\n", input);
return 0;
}

C: counting number of words (need help fixing)

I am new to C programming and trying to write a code for counting the number of words in a string.Here is my code for counting the number of codes.
#include<stdio.h>
#include<string.h>
void main()
{
int count=0,i,len;
char str[100];
printf("enter the sentence");
gets(str);
len=strlen(str);
for(i=0;i<=len;i++)
{
if(str[i]==' ')
count++;
}
printf("the number of words are :\t%d",count+1);
}
When my input is:Here is four words it works fine. it gives output
the number of words are : 4
My question is how do I handle "two consecutive spaces" between the word, "space at the beginning" of the input and "space at the last" of the input.
Instead of counting spaces, count the first non-space character of each word.
#include<stdio.h>
int main()
{
int count=0;
char str[100];
printf("enter the sentence");
gets(str);
char *cur= str;
for (;;)
{
while (*cur == ' ')
{
cur++;
}
if (*cur == 0)
{
break;
}
count++;
while (*cur != 0 && *cur != ' ')
{
cur++;
}
}
printf("the number of words are :\t%d",count);
return 0;
}
You can use:
while(str[i]==' '&&str[i]!=EOF)
{
count++;
i++;
}
instead of your if part. You also need to add these code before the for loop to read the beginning spaces.
I think the loop in the current form may not work properly,
It should be as follows,
for(i=0;i<len;i++)
{
if(i!=0)
{
if(str[i]==' ')
count++;
}
}
To check the other criteria change the code as follows,
for(i=0;i<len;i++)
{
if(str[i]==' ')
{
if(i!=0)
{
if(str[i+1]!=' ')
{
count++;
}
}
}
Just ignore spaces at the beginning and spaces directly after other spaces, and +1 if there are no spaces at the last.
#include <stdio.h>
#include <string.h>
// #include <stdlib.h>
int main() // void main is a bad practice
{
int count = 0, i, len, ignoreSpace;
char str[100];
printf("enter the sentence\n");
gets(str);
len = strlen(str);
ignoreSpace = 1; // handle space at the beginning
for(i = 0; i < len; i++) // not i<=len
{
if(str[i] == ' '){
if(!ignoreSpace){
count++;
ignoreSpace = 1; // handle two or more consecutive spaces
}
}else{
ignoreSpace = 0;
}
}
if( !ignoreSpace ) // handle space at the last
count++;
printf("the number of words are :\t%d\n", count); // +1 is moved to previous line
// system("pause");
return 0;
}
use strtok and first call of strtok use strtok(string," ") and for rest of calls use strtok(NULL, " \n")
You should count the transitions from space to non-space characters + a possible non-space character in the beginning itself.
#include<stdio.h>
#include<string.h>
int main()
{
int count=0,i,len, cur_is_spc;
char str[100];
printf("enter the sentence");
gets(str);
len=strlen(str);
cur_is_spc = 0; // 0, if current character is not space. 1, if it is.
for(i=0; str[i]!='\0'; i++)
{
if(str[i] != ' ')
{
switch(cur_is_spc) // currently holding value for previous character
{
case 0: count++; break; //count the spc->non-spc transitions
case 1: break;
default: cout << "Erroneous value"; exit(1);
}
cur_is_spc = 1; //updated for current character.
}
else
{
cur_is_spc = 0; //updated for current character.
}
}
printf("the number of words are :\t%d",count+1);
return 0;
}
Here, I am checking with only spaces. But there can be characters like newline, tab etc. How would your code handle them? Hint: use isspace() function.
/moreover, the transition can be done from non-alphabet characters to alphabet characters if you decide that words are made up of alphabets only. This approach is inherently flexible to suit your needs.
One quick way to do this is use strtok and break everything according to a predicate. This function satisfy all your requirements.
#include<stdio.h>
#include<string.h>
int countSpace(char* str){
int counter = 0;
char * newString;
newString= strtok (str, " "); // now the newString has the str except first word
while (newString != NULL){
counter++; // Put counter here to ignore the newString == NULL
// Or just -1 from the counter on main()
newString= strtok (NULL, " "); //Break the str in to words seperated by spaces
}
return counter;
}
void main(){
int count=0,i,len;
char str[100];
printf("Enter the sentence:\n");
fgets (str , 100 , stdin);
count = countSpace(str);
printf("The number of words are :\t%d\n",count);
return 0;
}
Thank you
Why not use strtok and bypass it altogether:
int main()
{
int num_words = 0;
char str_one[] = "This string has a trailing space ";
char str_two[] = " This string has a preceeding space";
char str_three[] = "This string contains two spaces consecutively twice!";
char delim[] = " ";
char *ret;
/* fgets() for user input as desired... */
if (( ret = strtok(str_one, delim)) != NULL )
{
while ( ret )
{
num_words++;
ret = strtok(NULL, delim);
}
}
else
{
/* no spaces, but might contain a word if the string isn't empty */
if ( str_one[0] != '\0' )
num_words = 1;
}
printf("str_one contains %i words\n", num_words);
num_words = 0;
...
return 0;
}
And by the way: main should ALWAYS return!!!

Resources