PWC Unit-3 (Arrays and Strings)
PWC Unit-3 (Arrays and Strings)
Subject
Basics of Logic Development
(IT3009)
Unit – 3
Arrays and Strings
CONTENTS
1. Basics of Array
2. One-dimensional Arrays
2.1. Declaration of One-dimensional Arrays
2.2. Initialization of One-dimensional Arrays
2.3. Solved Programs (One-dimensional Arrays)
3. Two-dimensional Arrays
3.1. Declaration of Two-dimensional Arrays
3.2. Initialization of Two-dimensional Arrays
3.3. Solved Programs (Two-dimensional Arrays)
4. Multidimensional Arrays
5. Basics of String
6. Declaration and Initializing String Variables
7. Reading Strings from Terminal
7.1. Using scanf() Function
7.2. Using getchar() and gets() Functions
8. Writing Strings to Screen
8.1. Using printf() Function
8.2. Using putchar() and puts() Functions
9. Arithmetic Operations on Characters
10. String Handling Functions (Built-in String Functions)
10.1. strcat() Function
10.2. strcmp() Function
10.3. strcpy() Function
10.4. strlen() Function
10.5. strrev() Function
10.6. Other String Functions
11. Solved Programs (Strings)
1. Basics of Array
An array is a collection of elements of similar data types referred by the same
variable name.
An array is a linear and homogeneous data structure. Linear data structure stores
its individual data elements in a sequential order in the memory. Homogeneous means
all individual data elements are of the same data type.
The individual elements of an array are referred by their index or sub-script value.
In C the index begins at zero and is always written inside square brackets.
For example, if marks of 10 students are stored in an array named mark, then
mark[0] refers to the marks of the first student, mark[1] refers to the marks of the
second student and mark[9] refers to the marks of the tenth student, that is, mark[n-1]
refers to the marks of nth student.
Advantages of Array:
• Unlike variable an array can store number of values under single name.
• The array elements are stored contiguously.
• Array index helps to access any random values from the array and perform
operations on it.
• An array is a flexible data structure, means we can perform addition or
removal of elements at any position.
Disadvantages of Array:
• Only elements of same data types can be stored in an array. We cannot
store elements of multiple data types in a single array.
• If array size is big, that much amount of memory gets reserved.
• Big size of arrays and multi-dimensional arrays are complicated to access
and manipulate.
• If there is need to store more elements than array size, then it is not possible
and shortage of memory occurs.
• If less elements are stored than array size then it leads to memory wastage.
Types of Arrays:
Arrays are categorized according to the dimensions used to define it. Here the
dimension indicates the number of rows and columns used to set size of an array.
There are following types of arrays:
• One-dimensional arrays
• Two-dimensional arrays
• Multidimensional arrays
2. One-dimensional Arrays
An array with single subscript is called as one-dimensional array.
data_type array_name[size];
where,
data_type = the type of data stored in the array
array_name = name of the array
size = maximum number of elements that an array can hold
For example,
float height[20];
declares the name as a character array (string) variable that can hold a
maximum number of 10 characters.
Suppose we read the following string constant into the string variable
name.
“WELL DONE”
Each character of the string is treated as an element of an array name
and is stored in the memory as follows:
‘W’ ‘E’ ‘L’ ‘L’ ‘’ ‘D’ ‘O’ ‘N’ ‘E’ ‘\0’
For example,
marks[0] = 35;
marks[1] = 70;
.
.
.
marks[9] = 86;
For example,
int marks[10] = {35,70,40,55,26,43,56,82,78,86};
35 70 40 55 26 43 56 82 78 86
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]
is equivalent to
int marks[3] = {45,66,84};
In such cases, the subscript is assumed to equal to the number of elements in the
array (3 in this case).
The elements which are not explicitly initialized are automatically set to zero.
Example:
int x[5] = {2,5};
implies
x[0] = 2;
x[1] = 5;
x[2] = 0;
x[3] = 0;
x[4] = 0;
#include<stdio.h>
int main()
{
int a[10],i,max,min;
for(i=0; i<10; i++) {
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
}
max=a[0];
min=a[0];
for(i=1; i<10; i++) {
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf("\nArray elements are: ");
for(i=0; i<10; i++)
printf("%4d",a[i]);
printf("\nMaximum Number = %d \nMinimum Number = %d",max,min);
return 0;
}
Output –
Enter number 1: 10
Enter number 2: 12
Enter number 3: 14
Enter number 4: 16
Enter number 5: 18
Enter number 6: 19
Enter number 7: 11
Enter number 8: 13
Enter number 9: 15
Enter number 10: 17
Array elements are: 10 12 14 16 18 19 11 13 15 17
Maximum Number = 19
Minimum Number = 10
Write a program to get n numbers and find sum and average of numbers.
#include<stdio.h>
int main()
{
int a[10],i,n;
float avg,sum=0;
printf("Enter value of n: ");
scanf("%d",&n);
for(i=0; i<n; i++) {
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
sum=sum+a[i];
}
avg=sum/n;
printf("\nArray elements are: ");
for(i=0; i<n; i++)
printf("%4d",a[i]);
printf("\nSum = %0.2f \nAverage = %0.2f",sum,avg);
return 0;
}
Output –
Enter value of n: 5
Enter number 1: 12
Enter number 2: 6
Enter number 3: 78
Enter number 4: 32
Enter number 5: 16
Array elements are: 12 6 78 32 16
Sum = 144.00
Average = 28.80
Write a program to find number of odd and even numbers from given n
numbers.
#include<stdio.h>
int main()
{
int a[10],i,n,odd=0,even=0;
printf("Enter value of n: ");
scanf("%d",&n);
for(i=0; i<n; i++) {
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
if(a[i]%2==0)
even++;
else
odd++;
}
printf("\nArray elements are: ");
for(i=0; i<n; i++)
printf("%4d",a[i]);
printf("\nNumber of Odd = %d \nNumber of Even = %d",odd,even);
return 0;
}
Output –
Enter value of n: 6
Enter number 1: 4
Enter number 2: 9
Enter number 3: 1
Enter number 4: 3
Enter number 5: 6
Enter number 6: 8
Array elements are: 4 9 1 3 6 8
Number of Odd = 3
Number of Even = 3
Write a program which finds maximum of n numbers and also finds how
many times maximum number is repeated.
#include<stdio.h>
int main()
{
int a[10],i,n,max,count;
printf("Enter value of n: ");
scanf("%d",&n);
for(i=0; i<n; i++) {
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
max=a[0];
}
for(i=1; i<n; i++) {
if(a[i]>max)
max=a[i];
}
count=0;
for(i=0; i<n; i++) {
if(max==a[i])
count++;
}
printf("\nArray elements are: ");
for(i=0; i<n; i++)
printf("%4d",a[i]);
printf("\nMaximum number = %d and is repeated %d times", max,
count);
return 0;
}
Output –
Enter value of n: 7
Enter number 1: 12
Enter number 2: 34
Enter number 3: 23
Enter number 4: 34
Enter number 5: 32
Enter number 6: 4
Enter number 7: 34
Array elements are: 12 34 23 34 32 4 34
Maximum number = 34 and is repeated 3 times
Write a program to sort given n numbers and display them in ascending and
descending order.
#include<stdio.h>
int main()
{
int a[10],i,j,n,temp;
printf("Enter value of n: ");
scanf("%d",&n);
for(i=0; i<n; i++) {
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
}
for(i=0; i<n-1; i++) {
for(j=i+1; j<n; j++) {
if(a[i]>a[j]) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\nNumbers in ascending order:\n");
for(i=0; i<n; i++)
printf("%4d",a[i]);
printf("\nNumbers in descending order:\n");
for(i=n-1; i>=0; i--)
printf("%4d",a[i]);
return 0;
}
Output –
Enter value of n: 7
Enter number 1: 8
Enter number 2: -2
Enter number 3: 12
Enter number 4: -6
Enter number 5: 34
Enter number 6: 26
Enter number 7: 15
Numbers in ascending order: -6 -2 8 12 15 26 34
Numbers in descending order: 34 26 15 12 8 -2 -6
3. Two-dimensional Arrays
• An array with two subscripts is called as two-dimensional array.
• 2D arrays are mostly used to perform matrix operations.
• A matrix has two subscripts – the first subscript denotes the number of rows and
the second subscript denotes the number of columns.
where,
data_type = the type of data stored in the array
array_name = name of the array
row_size = maximum number of rows in the array
column_size = maximum number of columns in the array
For example,
int table[2][3]; //implies 2 rows and 3 columns
declares the table to be an array containing 2 rows and 3 columns, i.e., total 6
real elements.
A user can view this array as below.
Column 0 Column 1 Column 2
Row 0 [0][0] [0][1] [0][2]
Row 1 [1][0] [1][1] [1][2]
table[0][0] 4000
table[0][1] 4002
table[0][2] 4004 Memory
table[1][0] 4006 Address
table[1][1] 4008
table[1][2] 4010
initialize first row data as {0,0,0} and second row data as {1,1,1}.
The above initialization is same as
int table[2][3] = {{0,0,0},{1,1,1}};
If the values are missing in an initializer, they are automatically set to 0. For
example, the statement
int table[2][3] = {{1,1},{2}};
will initialize the first two elements of the first row to 1, the first element of the
second row to 2, and all other elements to 0.
#include <stdio.h>
int main()
{
int a[3][3],i,j,max;
printf("Enter the elements of matrix A:\n");
for(i=0; i<3; i++) { //Get matrix data
for(j=0; j<3; j++) {
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0; i<3; i++) { //Display matrix row row-wise
for(j=0; j<3; j++) {
printf("%4d",a[i][j]);
}
printf("\n");
}
max=a[0][0];
for(i=0; i<3; i++) {
Output –
a[1][0] = 45
a[1][1] = 67
a[1][2] = 9
a[2][0] = 78
a[2][1] = 23
a[2][2] = 4
Matrix A:
6 12 23
45 67 9
78 23 4
#include <stdio.h>
int main()
{
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter the elements of matrix A:\n");
for(i=0; i<3; i++) { //Get first matrix data
for(j=0; j<3; j++) {
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
Output –
a[1][0] = 4
a[1][1] = 5
a[1][2] = 6
a[2][0] = 7
a[2][1] = 8
a[2][2] = 9
b[1][0] = 6
b[1][1] = 5
b[1][2] = 4
b[2][0] = 3
b[2][1] = 2
b[2][2] = 1
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
9 8 7
6 5 4
3 2 1
#include <stdio.h>
int main()
{
int a[3][3],i,j;
printf("Enter the elements of matrix:\n");
for(i=0; i<3; i++) { //Get matrix data
for(j=0; j<3; j++) {
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
Prepared by – Mr. Viral H. Panchal 16
Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0; i<3; i++) { //Display matrix row row-wise
for(j=0; j<3; j++) {
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nTranspose of A:\n");
for(j=0; j<3; j++) { //Display transpose of matrix
for(i=0; i<3; i++) {
printf("%4d",a[i][j]);
}
printf("\n");
}
return 0;
}
Output –
a[1][0] = 4
a[1][1] = 5
a[1][2] = 6
a[2][0] = 7
a[2][1] = 8
a[2][2] = 9
Matrix A:
1 2 3
4 5 6
7 8 9
Transpose of A:
1 4 7
2 5 8
3 6 9
#include <stdio.h>
int main()
{
int a[3][3],b[3][3],c[3][3],i,j,k,sum;
printf("Enter the elements of matrix A:\n");
for(i=0; i<3; i++) { //Get first matrix data
for(j=0; j<3; j++) {
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("Enter the elements of matrix B:\n");
for(i=0; i<3; i++) { //Get second matrix data
for(j=0; j<3; j++) {
printf("b[%d][%d] = ",i,j);
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0; i<3; i++) { //Display first matrix row row-wise
for(j=0; j<3; j++) {
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nMatrix B:\n");
for(i=0; i<3; i++) { //Display second matrix row row-wise
for(j=0; j<3; j++) {
printf("%4d",b[i][j]);
}
printf("\n");
}
for(i=0; i<3; i++) { //Finding multiplication of two matrices
for(j=0; j<3; j++) {
sum=0;
for(k=0; k<3; k++)
sum=sum+a[i][k]*b[k][j];
c[i][j]=sum;
}
}
Prepared by – Mr. Viral H. Panchal 18
Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings
Output –
a[1][0] = 4
a[1][1] = 5
a[1][2] = 6
a[2][0] = 7
a[2][1] = 8
a[2][2] = 9
b[1][0] = 2
b[1][1] = 2
b[1][2] = 2
b[2][0] = 3
b[2][1] = 3
b[2][2] = 3
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
1 1 1
2 2 2
3 3 3
4. Multidimensional Arrays
An array with more than two subscripts is called as multidimensional array.
For example, suppose we want to store 5 students marks information for 2 different
exams carried out in the term for 4 different subjects, this data can be stored by using
3-dimensional array like,
int marks[5][2][4];
where, 5 students, 2 exams, and 4 subjects. So, total entries in the array will
be 5*2*4 = 40.
5. Basics of String
A string is a sequence of characters that is treated as a single data item. Any group
of characters (except double quote sign) defined between double quotation marks is
a string constant. Example:
“Programming in C is fun.”
If we want to include a double quote in the string to be printed, then we may use
it with a back slash as shown below.
"\"Programming in C is fun.\""
For example,
printf(“\”Welcome\””);
“Welcome”
printf(“Welcome”);
Welcome
char string_name[size];
The reason that university had to be 13 elements long is that the string UKA
TARSADIA contains 12 characters and one element space is provided for the null
terminator. Note that when we initialize a character array by listing its elements, we
must supply explicitly the null terminator.
C also permits us to initialize a character array without specifying the number of
elements. In such cases, the size of the array will be determined automatically, based
on the number of elements initialized. For example, the statement
is permitted. In this case, the computer creates a character array of size 10, places the
value “CGPIT” in it, terminates with the null character, and initializes all other elements
to NULL. The storage will look like:
C G P I T \0 \0 \0 \0 \0
This will result in a compile time error. Also note that we can not separate the
initialization from declaration. That is,
char string[3];
string = “CGPIT”;
is not allowed. An array name cannot be used as the left operand of the assignment
operator.
char address[20];
scanf(“%s”, address);
The problem with scanf function is that it terminates its input on the first white space
it finds. A white space includes blanks, tabs, carriage returns, form feeds, and new
lines. Therefore, if the following line of text is typed in at the terminal,
UKA TARSADIA
then only the string “UKA” will be read into the array address, since the blank space
after the word “UKA” will terminate the reading of string.
The scanf function automatically terminates the string that is read with a null
character and therefore the character array should be large enough to hold the input
string plus the null character.
Note that in the case of character arrays, the ampersand (&) is not required before
the variable name.
The address array is created in the memory as shown below:
U K A \0 ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9
If we want to read the entire line “UKA TARSADIA”, then we may use two character
arrays of appropriate sizes. That is,
UKA TARSADIA
We can also specify the field width using the form %ws in the scanf statement for
reading a specified number of characters from the input string. Example:
scanf(“%ws”, name);
1. The width w is equal to or greater than the number of characters typed in. The
entire string will be stored in the string variable.
2. The width w is less than the number of characters in the string. The excess
characters will be truncated and left unread.
char name[10];
scanf(“%5s”, name);
U K A \0 ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9
T A R S A \0 ? ? ? ?
0 1 2 3 4 5 6 7 8 9
Example –
#include <stdio.h>
int main()
{
char word1[30], word2[30], word3[30], word4[30];
printf("Enter text:\n");
scanf("%s %s %s %s", word1, word2, word3, word4);
printf("\n");
printf("word1 = %s\nword2 = %s\n", word1, word2);
printf("word3 = %s\nword4 = %s\n", word3, word4);
return 0;
}
Output −
Enter text:
Uka Tarsadia University Bardoli
word1 = Uka
word2 = Tarsadia
word3 = University
word4 = Bardoli
char line[80];
scanf(“%[^\n]”, line);
printf(“%s”, line);
will read a line of input from the keyboard and displays the same on the screen.
char ch;
ch = getchar();
Example –
/* Write a program to read a line of text containing a series of
words from a terminal using getchar function */
#include <stdio.h>
int main()
{
char line[50], ch;
int c=0;
printf("Enter text. Press <Enter> at end\n");
do {
ch = getchar();
line[c] = ch;
c++;
} while(ch != '\n');
c = c-1;
line[c] = '\0';
printf("\n%s\n", line);
return 0;
}
Output −
The above program can read a line of text (up to maximum of 50 characters) into
the string line using getchar function. Every time a character is read, it is assigned to
Prepared by – Mr. Viral H. Panchal 26
Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings
its location in the string line and then tested for newline character. When the newline
character is read (signaling the end of line), the reading loop is terminated and the
newline character is replaced by the null character to indicate the end of character
string.
When the loop is exited, the value of the index c is one number higher than the last
character position in the string (since it has been incremented after assigning the new
character to the string). Therefore, the index value c-1 gives the position where the null
character is to be stored.
gets(str);
str is a string variable declared properly. It reads characters into str from the
keyboard until a new-line character is encountered and then appends a null character
to the string. Unlike scanf, it does not skip whitespaces. For example, the code segment
char line[50];
gets(line);
printf(“%s”, line);
reads a line of text from the keyboard and displays it on the screen. The last two
statements may be combined as follows:
printf(“%s”, gets(line));
C does not provide operators that work on strings directly. For instance, we cannot
assign one string to another directly. For example, the assignment statements
string2 = “XYZ”;
string1 = string2;
are not valid. If we really want to copy the characters in string2 into string1, we may
do so on a character-by-character basis.
Example –
/* Write a program to copy one string into another and count the
number of characters copied */
#include <stdio.h>
int main()
{
char string1[50], string2[50];
int i;
printf("Enter a string \n");
scanf("%s", string2);
for(i=0; string2[i]!='\0'; i++)
string1[i] = string2[i];
string1[i] = '\0';
printf("\n");
printf("%s", string1);
printf("\nNumber of characters = %d", i);
return 0;
}
Output −
Enter a string
CGPIT
CGPIT
Number of characters = 5
printf(“%s”, name);
We can also specify the precision with which the array is displayed. For instance,
the specification %10.4 indicates that the first four characters are to be printed in a
field width of 10 columns. However, if we include the minus sign in the specification
(e.g., %-10.4s), the string will be printed left-justified.
Prepared by – Mr. Viral H. Panchal 28
Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings
Example –
/* Write a program to store the string “Uka Tarsadia University”
in the array uni and display the string under various format
specifications */
#include <stdio.h>
int main()
{
char uni[24] = "Uka Tarsadia University";
printf("------------------------\n");
printf("%24s\n", uni);
printf("%5s\n", uni);
printf("%16.3s\n", uni);
printf("%-16.3s\n", uni);
printf("%16.0s\n", uni);
printf("%.6s\n", uni);
printf("%s\n", uni);
printf("------------------------\n");
return 0;
}
Output −
------------------------
Uka Tarsadia University
Uka Tarsadia University
Uka
Uka
Uka Ta
Uka Tarsadia University
------------------------
1. When the field which is less than the length of the string, the entire string is
printed.
2. The integer value on the right side of the decimal point specifies the number
of characters to be printed.
char ch = ‘A’;
putchar (ch);
The function putchar requires one parameter. This statement is equivalent to:
printf(“%c”, ch);
Another and more convenient way of printing string values is to use the function
puts declared in the header file <stdio.h>. This is one parameter function and invoked
as under:
puts (str);
where str is a string variable containing a string value. This prints the value of the string
variable str and then moves the cursor to the beginning of the next line on the screen.
For example, the program segment
char line[50];
gets(line);
puts(line);
reads a line of text from the keyboard and displays it on the screen. Note that the
syntax is very imple compared to using the scanf and printf statements.
is a valid statement. In ASCII, the value of ‘z’ is 122 and therefore, the statement will
assign the value 121 to the variable x.
We may also use character constants in relational expressions. For example, the
expression
ch >= ‘A’ && ch <= ‘z’
would test whether the character contained in the variable ch is an upper-case letter.
We can convert a character digit to its equivalent integer value using the following
relationship:
x = character – ‘0’;
where x is defined as an integer variable and character contains the character digit.
For example, let us assume that the character contains the digit ‘7’.
Then,
x = ASCII value of ‘7’ – ASCII value of ‘0’
= 55 – 48 = 7
The C library supports a function that converts a string of digits into their integer
values. The function takes the form
x = atoi(string);
number = “2022”;
year = atoi(number);
number is a string variable which is assigned the string constant “2022”. The function
atoi converts the string “2022” (contained in number) to its numeric equivalent 2022
and assign it to the integer variable year. String conversion functions are stored in the
header file <stdlib.h>.
Example –
/* Write a program which would print the alphabet set a to z and
A to Z in decimal and character form */
#include <stdio.h>
int main()
{
char c;
for(c=65; c<=122; c++) {
if(c>90 && c<97)
continue;
printf("|%3d - %c ", c, c);
}
printf("|\n");
return 0;
}
Output –
| 65 - A | 66 - B | 67 - C | 68 - D | 69 - E | 70 - F | 71 - G
| 72 - H | 73 - I | 74 - J | 75 - K | 76 - L | 77 - M | 78 - N
| 79 - O | 80 - P | 81 - Q | 82 - R | 83 - S | 84 - T | 85 - U
| 86 - V | 87 - W | 88 - X | 89 - Y | 90 - Z | 97 - a | 98 - b
| 99 - c |100 - d |101 - e |102 - f |103 - g |104 - h |105 - i
|106 - j |107 - k |108 - l |109 - m |110 - n |111 - o |112 - p
|113 - q |114 - r |115 - s |116 - t |117 - u |118 - v |119 - w
|120 - x |121 - y |122 - z |
It takes two arguments, the first one is a string variable and the second can be a
string variable or a string constant.
The characters of the second string are appended at the end of the first one.
Syntax –
strcat(string1,string2);
Here, string1 and string2 are character arrays (string2 can be string constant also).
The NULL character is removed from the end of string1 and string2 is stored from
this position.
Example –
/* Program to use strcat() function */
#include<stdio.h>
#include<string.h>
int main()
{
char string1[50],string2[50];
Output –
The comparison can be done either using the standard library function strcmp() or
the strings can be compared character by character.
Syntax –
strcmp(string1,string2);
It returns a 0 when strings are identical and returns the numeric difference between
the ASCII values of the first mismatch characters otherwise.
Example –
/* Program to use strcmp() function */
#include<stdio.h>
#include<string.h>
int main()
{
char string1[50],string2[50];
int diff;
printf("\nEnter the first string:\n");
gets(string1);
printf("\nEnter the second string:\n");
gets(string2);
diff=strcmp(string1,string2);
if(diff==0)
printf("\nBoth strings are same");
else
printf("\nBoth strings are different");
return 0;
}
Output –
Output –
Syntax –
strcpy(string1,string2);
Here, string1 is the target string which stores the contents of the source string string2.
The string2 may be a character array variable or a string constant. The string1 must
have a size greater than or equal to that of string2. The string2 is copied into the
string1 character by character and the process terminates on getting NULL character
(‘\0’) in the source string.
Note that the contents of the target string will be lost and source string remains
unchanged.
Example –
/* Program to use strcpy() function */
#include<stdio.h>
#include<string.h>
int main()
{
char string1[50],string2[50];
printf("\nEnter a string:\n");
gets(string1);
strcpy(string2,string1);
printf("\nCopied string is:\n%s",string2);
return 0;
}
Output –
Enter a string:
UKA TARSADIA UNIVERSITY
Copied string is:
UKA TARSADIA UNIVERSITY
In C, the function for finding the length of a string is strlen(). This function finds and
returns the number of characters in a string.
Syntax –
n=strlen(string);
Here, n is an integer variable which stores the values of the length of the string. The
string can be both a string variable or a string constant. The process of counting is
terminated on first occurrence of NULL character (‘\0’).
Example –
/* Program to find the length of a given string using strlen()
function */
#include<stdio.h>
#include<string.h>
int main()
{
char string1[50];
int n;
printf("\nEnter a string:\n");
gets(string1);
n=strlen(string1);
printf("\nThe length of string is %d",n);
return 0;
}
Output –
Enter a string:
Uka Tarsadia University
The length of string is 23
Syntax –
strrev(string);
Example –
/* Program to print a given string in reverse order using strrev()
function */
#include<stdio.h>
#include<string.h>
int main()
{
char string1[50];
printf("\nEnter a string:\n");
gets(string1);
strrev(string1);
printf("\nReversed string is:\n%s",string1);
return 0;
}
Output –
Enter a string:
cgpit
• strncpy()
In addition to the function strcpy() that copies one string to another, we have
another function strncpy() that copies only the left-most n characters of the source
string to the target string variable.
strncpy(s1,s2,5);
This statement copies the first 5 characters of the source string s2 into the target
string s1.
• strncmp()
A variation of the function strcmp() is the function strncmp(). This function has
three parameters as illustrated in the function call below:
strncmp(s1,s2,n);
• strncat()
strncat(s1,s2,n);
This call will concatenate the left-most n characters of s2 to the end of s1.
• strstr()
strstr(s1,s2);
strstr(s1,”ABC”);
The function strstr() searches the string s1 to see whether the string s2 is contained
in s1. If yes, the function returns the position of the first occurrence of the sub-string.
Otherwise, it returns a NULL pointer. Example:
strchr(s1,’m’);
will locate the first occurrence of the character ‘m’ and the call
strrchr(s1,’m’);
will locate the last occurrence of the character ‘m’ in the string s1.
• strupr()
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, vowels = 0;
printf("Enter a string: \n");
gets(str);
for(i = 0; str[i]; i++) {
if(str[i]=='a'|| str[i]=='e'||str[i]=='i'||
str[i]=='o'|| str[i]=='u'||str[i]=='A'||
str[i]=='E'||str[i]=='I'||str[i]=='O' ||str[i]=='U') {
vowels++;
}
}
printf("Total number of vowels: = %d\n",vowels);
return 0;
}
Output –
Enter a string:
Uka Tarsadia University
Total number of vowels: = 10
#include<stdio.h>
#include<string.h>
int main()
{
int i,n;
char str[50];
printf("Enter the String to get reversed:\n");
gets(str);
n=strlen(str);
printf("\nReversed string is:\n");
for(i=n-1; i>=0; i--) {
printf("%c",str[i]);
}
return 0;
}
Output –
#include<stdio.h>
#include<string.h>
int main()
{
char string[50];
char ch='p';
printf("\nEnter a string:\n");
gets(string);
if(strchr(string,ch))
printf("The character %c is at position: %d\n",
ch, strchr(string,ch)-string+1);
else
printf("\nThe character is not found");
return 0;
}
Output –
Enter a string:
cgpit
The character p is at position: 3
#include<stdio.h>
#include<string.h>
int main()
{
char string[50],chr,repl_chr;
int i=0;
printf("\nEnter a string: ");
gets(string);
printf("\nEnter a character to be replaced: ");
scanf("%s",&chr);
printf("\nEnter replacement character: ");
scanf("%s",&repl_chr);
while(string[i]!='\0') {
if(string[i]==chr) {
string[i]=repl_chr;
}
i++;
}
printf("\nModified string after replacement is: %s",
string);
return 0;
}
Output –
#include<stdio.h>
#include<string.h>
int main()
{
char str[50],ch;
int i,j;
printf("\nEnter a string: ");
gets(str);
printf("\nEnter a character to delete from string: ");
scanf("%c",&ch);
//Accessing each element of string to perform delete operation
for(i=0; i<strlen(str); i++) {
if(ch==str[i]) {
/*After deleting user provided element moving each element
one step forward to fill it's place */
for(j=i;j<strlen(str);j++)
str[j]=str[j+1];
}
}
printf("\nString after deleting character: %s",str);
return 0;
Output –
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
printf("\nEnter a string: ");
gets(str);
printf("\nThe string in upper case: %s",strupr(str));
return 0;
}
Output –
#include<stdio.h>
#include<string.h>
int main()
{
char str1[50],str2[50];
int diff;
printf("\nEnter a string: ");
gets(str1);
strcpy(str2,str1);
strrev(str2);
diff=strcmp(str1,str2);
if(diff==0)
printf("\nString is a palindrome");
else
printf("\nString is not a palindrome");
return 0;
}
Output –
Output –