Pages

Strings


In programming languages, a string means a sequence of characters, either as a literal constant or as a kind of variable. In C programming language, a string can be represented by character array type of variable.

Let's learn Top C Programming String Programs

In C language, a string is represented by character array. Popular C string processing programs are given at the bottom of this webpage.

Following C programs are based on important concepts related to a String:

//C Program to demonstrate String Initialization.

#include <stdio.h> 
#include<string.h>
int main () 
{ 
 char name[10];
 name[0]='H';
 name[1]='E';
 name[2]='L';
 name[3]='L';
 name[4]='O';
 name[5]='\0';
 printf("Greeting message: %s", name); 
 return 0;
}

Output of program:

HELLO




// C program to read and print your first name.

#include<stdio.h>
#include<string.h>
int main()
{
 char str[10];
 printf("Enter your name:");
 scanf("%s",str);
 printf("Your name is %s \n",str);
 return 0;
}

Output of program:

Enter your name:ABC
ABC


//C program to convert given uppercase letters to lowercase.

#include<stdio.h>
#include<string.h>
int main()
{
 char str1[10]="ABCD";
 int i;
 for(i=0; i<4; i++)
 {
  printf("%c",str1[i]+32);
 }
 return 0;
}

Output of program:

abcd


//Program to count characters in given string. 
//It will count 'A' in given string AHMEDABAD.

#include<stdio.h>
#include<string.h>
int main()
{
  char str[20]="AHMEDABAD";
  int i,cnt=0,len=0;
 
  len=strlen(str);
 
  for(i=0; i < len; i++)   {
      if( str[i] == 'A')
          cnt++;     
  }
  printf("Total A in given string : %d",cnt);
 return 0;
}

Output of program:

Total A in given string : 3

//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?



 
 



No comments:

Post a Comment