Saturday, January 30, 2016

C program to count words in a given string.

#include<stdio.h>
#include<stdlib.h>

int main(){

char str1[80]="Hello Student How are you?", *token ;
const char s[2] = " ";
    
int counter=0;
printf("Given String = %s",str1);
token = strtok(str1,s);
while (token != NULL)
{
counter++;
token = strtok(NULL, s);
}
printf("\nTotal words in a given string is %d", counter );
 return 0;
}

Output of program:
Given String = Hello Student How are you?
Total words in a given string is 5

C program to separate words (tokens) from a given string

#include<stdio.h>
#include<stdlib.h>
int main()
{
      char str1[80]="Hello Student How are you?";
   const char str[80] = "", s[2] = " ";
   char *token;
   int counter=1;
   
   token = strtok(str1,s);
   while (token != NULL)
   {
printf("Token %d = %s \n", counter++, token);
token = strtok(NULL, s);
   }
   return 0;
}

Output of program

Token 1 = Hello
Token 2 = Student
Token 3 = How
Token 4 = are
Token 5 = you?


You may also like to learn following programs:

Friday, January 29, 2016

Divide given string into three equal parts using for loop.

C program to divide given string into three equal parts using for loop.


#include<stdio.h>
#include<string.h>
int main()
{
 char str[30];
 int i,j,cnt=0;
 gets(str);
 //Read 30 characters to avoid extra characters in output. 
 for(i=0; i<3; i++)
 {
  for(j=0; j<10; j++)
   printf("%c",str[cnt++]);
  printf("\n");
 }
 return 0;
}


Monday, January 25, 2016

C program to read file line by line.

This program will read and print content of the "test.txt" file. 

Note: Save source code (.c) file and "test.txt" file in same folder.

#include<stdio.h> 
int main()
{
 FILE *f1, *fopen();
 char str1[80];
 
 f1 = fopen("test.txt","r");

 while(fgets(str1,80,f1)!=NULL)
 {
  printf("%s",str1); 
 }
 fclose(f1);
 return 0;
}

C program to read one line from a file.

This program will read and print one line from a "test.txt" file.   

#include<stdio.h>
int main(){
 
 FILE *f1, *fopen();
 char str1[80];
 
 f1 = fopen("test.txt","r");
 //Following line will read one line from a text.txt file. 
 fgets(str1,80,f1);
 puts(str1);  

 fclose(f1);
 return 0;
}