You are on page 1of 12

C Programming : String

In C programming, array of characters are called strings in other words a string is a collection of characters in double
quotes. Each string in c language is terminated by null character \0. When user enter a string the compiler
automatically insert a null character at the end of string for specific the end of string. For example:
"DILPREET"
Here, "c string" is a string. When, compiler encounters strings, it appends null character at the end of string.
D

\0

Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.
char s[5];

The declaration of string contain char as datatype , string variable name and size of the string in subscript. The size of
string specific the maximum numbers of characters (include null character) at can be store in string.
Strings can also be declared using pointer. In that case there is no need to specific the string size
char *p

Initialization of strings
Initialization means providing the initial value to string at the time of declaration of string. In C, string can be
initialized in different number of ways.
char c[]="abcd";
char c[5]="abcd";

OR,
OR,

char c[]={'a','b','c','d','\0'}; OR,


char c[5]={'a','b','c','d','\0'};

String can also be initialized using pointers


char *c="abcd";

Reading Strings from user.


Like a numerical variable we can also input a string at run time of a program. In that case we can use formatted input
function scanf() with %s as format specifire or gets() non-formatted formatted function the basic difference between
scanf() and gets() that scanf function only accept a word as string and gets() can Accept a line of text as string.
char c[20];
scanf("%s",c);

String variable c can only take a word. It is because when white space is encountered, the scanf()function terminates.
char c[20];
gets(c);
string variable c can accept a line of text it is because terminate character for gets() is enter so it accept all characters
include space in string until enter pressed.
Write a C program to illustrate how to read string from terminal.
#include <stdio.h>
void main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
}

Output
Enter name: Dilpreet Singh
Your name is Dilpreetg
Here, program will ignore Singh because, scanf() function takes only string before the white space.

Reading and writing a line of text


C program to read line of text manually.
#include <stdio.h>
void main()
{
char name[30],ch;
int i=0,n=0;
printf("Enter name: ");
do
{
ch=getchar();
name[i]=ch;
i++;
} while(ch!='\n');
i--;
name[i]='\0';
printf(Name :);
while(name[n]!=\0)
{
putchar(name[n]);
n++;
}
}
There are predefined functions gets() and puts() in C language to read and display string respectively. gets()
and puts() function handle string, both these functions are defined in "stdio.h" header file.
void main(){
char name[30];
printf("Enter name: ");
gets(name);
printf("Name: ");
puts(name);
}
Output
Enter name: Rajeev kumar

Name: Rajeev kumar


String Manipulations In C Programming Using Library Functions
Strings are often needed to be manipulated by programmer according to the need of a problem. All string manipulation
can be done manually by the programmer but, this makes programming complex and large. To solve this, the C supports
a large number of string handling functions.
There are many functions defined in "string.h" header file. Few commonly used string handling functions are as below:
Function

Work of Function

strlen()

Calculates the length of string

strcpy()

Copies a string to another string

strcat()

Concatenates(joins) two strings

strcmp()

Compares two string

strlwr()

Converts string to lowercase

strupr()

Converts string to uppercase

Strings handling functions are defined under "string.h" header file, i.e, you have to include the code to run string
handling functions.
#include <string.h>

strlen()
In C, strlen() function calculates the length of string. It takes only one argument,
i.e, string name.
Defined in Header File <string.h>
Syntax of strlen()
temp_variable = strlen(string_name);
Function strlen() returns the value of type integer.

Example of strlen()
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
char c[20];
3

printf("Enter string: ");


gets(c);
printf("Length of string a=%d \n",strlen(a));
printf("Length of string b=%d \n",strlen(b));
printf("Length of string c=%d \n",strlen(c));
getch();
}
Output
Enter string: String
Length of string a=7
Length of string b=7
Length of string c=6
strcat()
In C programming, strcat() concatenates(joins) two strings. It takes two arguments,
i.e, two strings and resultant string is stored in the first string specified in the
argument.
Syntax of strcat()
strcat(first_string,second_string);
Example of strcat()
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char str1[]="Raj ", str2[]="Kumar";
strcat(str1,str2);
puts(str1);
getch();
}
Output
Raj Kumar
strcmp()
In C programming, strcmp() compares two string and returns value 0, if the two
strings are equal. Function strcmp() takes two arguments, i.e, name of two string
to compare.
Syntax of strcmp()
temp_varaible=strcmp(string1,string2);
Example of strcmp()
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
4

char str1[30],str2[30];
int n;
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
n=strcmp(str1,str2);
if(n==0)
printf("Both strings are equal");
else
{
printf("Strings are unequal");
printf(diff. in mismatch character is=%d,n);
}
getch();
}
Output
Enter first string: Apple
Enter second string: Orange
Strings are unequal.
Diff. in mismatch character is -14
If two strings are not equal, strcmp() returns positive value if ASCII value of first
mismatching element of first string is greater than that of second string and
negative value if ASCII value of first mismatching element of first string is less than
that of second string.
strcpy()
Function strcpy() copies the content of one string to the content of another
string. It takes two arguments.
Syntax of strcpy()
strcpy(destination,source);
Here, source and destination are both the name of the string. This statement,
copies the content of string source to the content of string destination.
Example of strcpy()
#include <stdio.h>
#include <string.h>
void main()
{
char a[10],b[10];
printf("Enter string: ");
gets(a);
strcpy(b,a);
printf("Copied string: ");
puts(b);
}
Output

//Content of string a is copied to string b.

Enter string: Programming


Copied string: Programming
strlwr()
In C programming, strlwr() function converts all the uppercase characters in that
string to lowercase characters. The resultant from strlwr() is stored in the same
string.
Syntax of strlwr()
strlwr(string_name);
Example of strlwr()
#include <stdio.h>
#include <string.h>
void main(){
char str1[]="LOWer Case";
puts(strlwr(str1));
//converts to lowercase and
displays it.
}
Output
lower case
Function strlwr() leaves the lowercase characters as it is and converts uppercase
characters to lowercase.
strupr()
In C programming, strupr() function converts all the lowercase characters in that
string to uppercase characters. The resultant from strupr() is stored in the same
string.
Defined in Header File: <string.h>
Syntax of strupr()
strupr(string_name);
Example of strupr()
#include <stdio.h>
#include <string.h>
void main()
{
char str1[]="UppEr Case";
puts(strupr(str1));
}
Output

//Converts to uppercase and displays it.

UPPER CASE
Function strupr() leaves the uppercase characters as it is and converts lowercase
characters to uppercase.
6

Source Code to Calculated Length without Using strlen() Function


#include <stdio.h>
void main()
{
char s[1000],i;
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d",i);
}
Output
Enter a string: Programiz
Length of string: 9
Source Code to Copy String Manually or without strcpy function
#include <stdio.h>
void main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i=0; s1[i]!='\0'; ++i)
{
s2[i]=s1[i];
}
s2[i]='\0';
printf("String s2: %s",s2);
}
Output
Enter String s1: programiz
String s2: programiz
Source Code to Concatenate Two Strings Manually
#include <stdio.h>
void main()
{
char s1[100], s2[100], i, j;
printf("Enter first string: ");
scanf("%s",s1);
printf("Enter second string: ");
scanf("%s",s2);
for(i=0; s1[i]!='\0'; ++i); /* i contains length of string s1. */
for(j=0; s2[j]!='\0'; ++j, ++i)
{
s1[i]=s2[j];
}
s1[i]='\0';
printf("After concatenation: %s",s1);
7

}
Output
Enter first string: string
Enter second string: programs
After concatenation: stringprogram
Source Code to Find Number of Vowels, Consonants, Digits and White Space Character
#include<stdio.h>
void main()
{
char line[150];
int i,v,c,ch,d,s,o;
o=v=c=ch=d=s=0;
printf("Enter a line of string:\n");
gets(line);
for(i=0;line[i]!='\0';++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E' || line[i]=='I' ||
line[i]=='O' || line[i]=='U')
++v;
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
++c;
else if(line[i]>='0'&&c<='9')
++d;
else if (line[i]==' ')
++s;
}
printf("Vowels: %d",v);
printf("\nConsonants: %d",c);
printf("\nDigits: %d",d);
printf("\nWhite spaces: %d",s);
}
Output
Enter a line of string:
This program is easy 2 understand
Vowels: 9
Consonants: 18
Digits: 1
White spaces: 5
Source Code to Find the Frequency of Characters

#include <stdio.h>
void main()
{
char c[1000],ch;
int i,count=0;
printf("Enter a string: ");
gets(c);
printf("Enter a characeter to find frequency: ");
scanf("%c",&ch);
for(i=0;c[i]!='\0';++i)
{
if(ch==c[i])

++count;
}
printf("Frequency of %c = %d", ch, count);
}

Output
Enter a string: This website is awesome.
Enter a frequency to find frequency: e
Frequency of e = 4

Passing Strings to Functions


String can be passed to function in similar manner as arrays as, string is also an array. Learn more
aboutpassing array to a function .
#include <stdio.h>
void Display(char ch[]);
int main(){
char c[50];
printf("Enter string: ");
gets(c);
Display(c); // Passing string c to function.
return 0;
}
void Display(char ch[]){
printf("String Output: ");
puts(ch);
}
Here, string c is passed from main() function to user-defined function Display(). In function
declaration,ch[] is the formal argument.

What are the storage classes in C? Explain in detail with necessary examples.
In C, not only variables have data type, they also have a storage class associated with them. There are four storage classes in C.
They are
1. Automatic variables (auto)
2. External variables (extern)
3. Static variables (static)
4. Register variables (register)
1. Automatic variables: Declared inside a function in which they are utilized. They are created when the function is called and
destroyed automatically when the function is exited, hence the name automatic. Automatic variables are therefore private (or local)
to a function in which they are declared. Because of this property, automatic variables are also referred to as local or internal
variables. A variable declared inside a function without storage class specification is, by default, an automatic variable. Eg: int
number; is equivalent to auto int number;
Keyword: auto is the keyword used for automatic variables. One important feature of automatic variables is that their value cannot
be changed accidentally by what happens in some other function in the program. This ensures that we may declare and use the same
variable name in different functions in the same program without causing any confusion to the compiler.
void function1(void);
main()
{
int m=100; //m is local to main()
function1();
printf(%d \n,m);
getch();
}
void function1()
{ int m=10; //m is local to function1()
printf(%d \n,m);
}
Output: 10 //value of m in function1()
100 //value of m in main()
2. External variables: External variables are those that are alive and active throughout the program. They are also known as global
variables. Unlike, local variables, global variables are accessed by any function in the program. External variables are declared
outside a function.
Keyword: extern
For example, int number;
float average=10.0;
main()
{ }
function1()
{ . }
function2()
{ . }
The variables number and average are global variables since they are declared outside the main(). They are globally available for
use in all three functions.
In case a local variable and a global variable have a same name, then the local variable will have precedence over the global one in
the function where
it is declared. The main function cannot access the variable if it has been declared after the main function. This problem can be
solved by declaring the variable with the storage class extern. void printline(void); is equivalent to extern void printline(void);

10

3. Static variables: The value of the static variables persists until the end of
the program. A variable can be declared using the keyword static.
Eg: static int x;
static float y;
A static variable may be either an of internal type or external type depending
on the place of declaration.
Internal static variables are similar to the auto variables except that they are alive through out the program. Hence, they can be
used to retain values between function calls.
Static variable is initialized only once, when the program is compiled. It is never initialized again.
An external static variable is declared outside of all functions and is available to all the functions in that program. The difference
between a static external variable and a simple external variable is that the static external variable is available only within the file
where it is defined while the simple external variable can be accessed by other files. Program to illustrate static variable:
void stat();
void main()
{
int i;
for(i=0;i<3;i++)
stat();
}
void stat()
{
static int x=0;
x=x+1;
printf(x=%d \n,x);
}
Output: x=1
x=2
x=3
4. Register variables: A variable that should be kept in one of the machines registers, instead of keeping in the memory (where
variables are normally stored) has to be declared using the storage class register. Eg: register int count;
Advantage: Since register access is much faster than memory access, it
leads to faster execution.
Note: Most compilers allow only int or char variables to be placed in the
register. Since, only a few variables can be placed in a register, it is important to carefully select the variables for this purpose.
However, C compiler automatically converts the register variables into non-register variables once the limit is reached.
Write a short note on nested blocks.
A set of statements enclosed in a set of braces is known as a block or a compound statement. A block can has its own declarations
and other statements. It is also possible to have a block of such statements inside the body of a function or another block, thus
creating what is known as nested blocks as shown below.
main()
{
int a=10;
int b=10;

{ int a=0;
int c=a+b;
printf(Inner block,c=%d\n,c);
.}
c=a+b;
printf(Outer block,c=%d,c);
}
Output: Inner block,c=10
Outer block,c=20
Explanation: The scope of variables inside the inner block is pertained till the end of the inner block. So here, a is declared and
initialized to 0 so, c= a+b that means c=0+10 =10. The scope of outer block variables is pertained till the end of the program. So,
after inner block c= a+b. Here, a=10 and b= 10 are there,so c=10+10=20.
3.22 Define the terms scope, visibility and lifetime.
Scope: The region of a program in which a variable is available for use. Inner block Outer block
Visibility: The programs ability to access a variable from the memory.
Lifetime: The lifetime of a variable is the duration of time in which a variable
exists in the memory during execution.

11

12

You might also like