Nothing Special   »   [go: up one dir, main page]

Bpops103 Module4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

Module-4

Chapter-13
STRING:
13.1 Introduction.
13.2 String taxonomy.
13.3 Operations on strings.
13.4 Miscellaneous string and character functions
13.5 Arrays of strings.

By-
Dr. SANTOSH K C
Assoc. Prof.
CSE, BIET
Davangere-04
13.1 Introduction.
• “A string is a sequence of characters enclosed
within double quotes”. or
• “String is an array of characters and terminated by
NULL character which is denoted by ‘\0’.
• In C, a string is a null-terminated character array. This
means that after the last character, a null character
('\0') is stored to signify the end of the character
array.
Figure below shows the difference between
character storage and string storage.
• Like we use subscripts (also known as index) to
access the elements of an array, we can also use
subscripts to access the elements of a string. The
subscript starts with a zero (0). All the characters of a
string are stored in successive memory locations.
Figure shows how str[] is stored in the memory.
• ASCII code of a character is stored in the memory
and not the character itself. So, at address 1000, 72
will be stored as the ASCII code for H is 72. The
statement char str[] = "HELLO";
• Syntax:
• the general form of declaring a string is
• char str[size];
• The other way to initialize a string is to initialize it as an
array of characters.
For example, char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};
Here, the compiler will automatically calculate the
size based on the number of characters.

• We can also declare a string with size much larger


than the number of elements that are initialized.
For example, consider the statement below.
char str [10] = "HELLO";

• consider the following statements: char str[3];


str = "HELLO";
The above initialization statement is illegal in C and
would generate a compile-time error.
Reading Strings
• If we declare a string by writing char str[100]; Then str can
be read by the user in three ways:
• using scanf() function,
• using gets() function, and
• using getchar(),getch()or getche() function repeatedly.

using scanf()
• Strings can be read using scanf() by writing scanf("%s", str);
• Unlike int, float, and char values, %s format does not
require the ampersand before the variable str.
• The main pitfall of using this function is that the function
terminates as soon as it finds a blank space. Therefore we
cannot read the complete sentence using scanf() function.
using gets()
• The string can be read by writing gets(str);
• gets() is a simple function that overcomes the
drawbacks of the scanf() function.
• gets() function is used to read a sequence of
characters (string) with spaces in between.
• The ‘gets()’ function allows us to read an ‘entire
line’ of input including whitespace characters.
Writing Strings
• Strings can be displayed on the screen using the
following three ways:
• using printf() function
• using puts() function, and
• using putchar() function repeatedly

using printf()
• Strings can be displayed using printf() by writing
printf("%s", str);
• We use the format specifier %s to output a string.
using puts()
• A string can be displayed by writing puts(str);
• puts() is a simple function that overcomes the
drawbacks of the printf() function.
• The puts() function writes a line of output on the
screen. It terminates the line with a newline
character (‘\n’).
13.2 String Taxonomy

• Fixed-length strings
• Variable-length strings
13.3 Operations on Strings
Finding Length of a String
• The number of characters in a string constitutes the
length of the string.
For example, LENGTH("C PROGRAMMING IS FUN")
will return 20. Note that even blank spaces are
counted as characters in the string.

• Figure 4.3 shows an algorithm that calculates the


length of a string.
Converting Characters of a String into Upper Case
• In the memory ASCII codes are stored instead of the
real values. The ASCII code for A–Z varies from 65 to
91 and the ASCII code for a–z ranges from 97 to 123.
So, if we have to convert a lower case character into
uppercase, we just need to subtract 32 from the
ASCII value of the character.
Converting Characters of a String into Lower Case
Concatenating Two Strings to Form a New String
If s1 and s2 are two strings, then concatenation
operation produces a string which contains
characters of s1 followed by the characters of s2.
Comparing Two Strings
If S1 and S2 are two strings, then comparing the two
strings will give either of the following results:
(a) S1 and S2 are equal
(b) S1>S2
(c) S1 <S2
Appending a String to Another String
Appending one string to another string involves
copying the contents of the source string at the end
of the destination string.

Reversing a String
If S1="HELLO", then reverse of S1="OLLEH".
To reverse a string, we just need to swap the first
character with the last, second character with the
second last character, and so on.
Inserting a String in Another String
The insertion operation inserts a string S in the main text T
at the kth position. The general syntax of this operation
is INSERT(text, position, string).
• For example, INSERT("XYZXYZ",3, "AAA") = ? ?

Deleting a string from the Main String


The deletion operation deletes a substring from a given
text.
We can write it as DELETE(text, position, length).
• For example, DELETE("ABCDXXXABCD", 4, 3) = ? ?
13.4 Miscellaneous String and
Character Functions
13.4.1 Character Manipulation Functions
13.4.2 String Manipulation Functions
The standard library ‘string.h’ contains many functions for
the string manipulation.

strlen(str): The length of a string


• The ‘strlen()’ function can be used to find the length of
the string in bytes.
• This function calculates the length of the string
excluding the ‘null character’. i.e., the function returns
the number of characters in the string.
Ex: Write a C program to demonstrate the usage of
strlen().
#include<stdio.h>
#include<string.h>
void main()
{
char str[] =“HELLO WORLD!”;
printf(“\n The length of the string is: %d”, strlen(str));
}

Output:
The length of the string is: ??
strcpy ( ): String Copy
• The ‘strcpy()’ function copies the contents of source
string str2 to destination string str1 including ‘\0’.
• The strcpy() function copies characters from the
source string to the destination string until it finds null
character. It returns the argument str1.

Syntax: char strcpy(char *str1, char *str2);

Where,
• str1: it is the destination string
• str2: it is the source string.
Ex: Write a C program to demonstrate the usage of
strcpy().
#include<stdio.h>
#include<string.h>
void main( )
{
char str1[10], str2[10]= “BIET”;
strcpy(str1,str2);
printf(“The Source String=%s\n The Destination
String=%s”, str1,str2);
}

Output:
The Source String= BIET
The Destination String= BIET
strncpy(str1,str2,n): String Number Copy
• ‘strncpy()’ function is used to copy ‘n’ characters from
the source string str2 to the destination string str1.

Syntax : char *strncpy(char str1, char str2, size n);

Where,
• str1: it is the destination string.
• str2: it is the source string.
• n: n is the number of characters to be copied into
destination string.
Ex: Write a C program to demonstrate the usage of
strncpy().
#include<stdio.h>
#include<string.h>
void main()
{
char str1[10], str2[10]= “Computer”;
strncpy(str1,str2,3);
printf (“The Source String=%s\n The Destination
String=%s”, str1,str2);
}

Output:
The Source String= Computer
The Destination String= ??
strcmp(str1,str2): String Compare
• This function is used to compare two strings.
• The comparison starts with first character of each
string. The comparison continues till the
corresponding characters differ or until the end of
the character is reached.
Ex:
• “car” and “cat” are different strings. The characters
‘r’ and ‘t’ have different ASCII values. It returns
negative value since ASCII value of ‘r’ is less than
the ASCII value of ‘t’.
• “car” and “car” are same, the function returns 0.

• “cat” and “car” are different strings. The characters


‘t’ and ‘r’ have different ASCII values. It returns
positive value since ASCII value of ‘t’ is greater than
the ASCII value of ‘r’.
Ex: Write a C program to demonstrate the usage of
strcmp().
#include<stdio.h>
#include<string.h>
void main()
{
char str1[10]=”Hello”; char str2[10]=”Hey”;
if(strcmp(str1,str2)==0)
printf(“The two strings are identical”);
else
}
printf(“The two strings are not identical”);
}
Output:
The two strings are not identical
Example to read a string using gets() and
print it on the console using puts()
#include<stdio.h>
#include <string.h>
int main()
{
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
13.4 Arrays of Strings
• In C programming String is a 1-D array of characters
and is defined as an array of characters.
• But an array of strings in C is a two-dimensional array
of character types.

An array of strings is declared as


<data_type> <array_name> [row_size][column_size];
• Here, the first index row_size will specify how many
strings are needed and the second index
column_size will specify the length of every individual
string.
Ex: char name[5][10];
name[5][10] = {"Ram", "Mohan", "Shyam", "Hari",
"Gopal"};

In the memory, the array will be stored as shown in Fig. 4.13.


Write a C Program to Read and Print the Names of N Students
of a Class.
#include<stdio.h>
void main()
{
char names[5][10];
int i, n;
printf(“\n Enter the number of students : “);
scanf(“%d”,&n);
printf(“\n Enter the names of students :”);
for(i=0;i<n;i++)
{
scanf(“%s”,names[i]);
}
printf(“\n Names of the students are : \n”);
for(i=0;i<n;i++)
puts(names[i]);
}
Module-4 (Cntd…)
Chapter-14
POINTERS
14.1 Introduction.
14.2 Declaring Pointer Variables.
14.3 Types of Pointer.
14.4 Passing Arguments to Function Using Pointers.

By-
Dr. SANTOSH K C
Assoc. Prof.
CSE, BIET
Davangere-04
14.1 Introduction
“A pointer is a variable that holds the address of
another variable”. or
“A pointer is a variable that contains the memory
location of another variable”.

Therefore, a pointer is a variable that represents the


location of a data item, such as a variable or an array
element.
14.2 Applications of pointer
✓ Pointers are used to pass information back and forth
between functions.
✓ Pointers enable the programmers to return multiple data
items from a function via function arguments.
✓ Pointers provide an alternate way to access the
individual elements of an array.
✓ Pointers are used to pass arrays and strings as function
arguments.
✓ Pointers are used to create complex data structures,
such as trees, linked lists, linked stacks, linked queues, and
graphs.
✓ Pointers are used for the dynamic memory allocation of
a variable.
14.3 Declaring Pointer Variables
• The general syntax of declaring pointer variables can
be given as below.
data_type *ptr_name;

• Here, data_type: is the data type of the value that the


pointer will point to. It can be int, float, char etc.
• Asterisk (*): It tells the compiler that we are declaring
a pointer variable.
• pointer_variable_name: It is the name of the pointer
variable.
Example:
1. int *ptr; // declares a pointer variable ptr of integer type.
2. 2. float *temp; // declares a pointer variable temp of floating
type.
Operators used with Pointers:
The two basic operators used with pointers are:
i. The Address of operator (&): By using the address of
(&) operator, we can determine the address of the
variable.
ii. The Indirection operator (*): It gives the value stored
at a particular address.

Example: Memory layout:


int a=3;
int *ptr;
ptr=&a;
Example Program: Write a C program to print value and
address of the variable using pointers.
#include<stdio.h>
void main ()
{
int a=20, *ptr;
ptr = &a; //ptr1 is a pointer to variable a
printf(“The address of a=%d and value of
a=%d\n”,ptr,*ptr);
}
Output:
The address of a=65530 and value of a=20
Initializing a Pointer Variable
• Initialization of a pointer variables by assigning the address
of other variable to them. However these variables must be
declared in the program.
Syntax: data_type * ptr_name = address_of_variable;

where,
• data_type: It can be int, float, char etc.
• Asterisk (*): It tells the compiler that we are declaring a
pointer variable.
• ptr_name: It is the name of the pointer variable.
• address_of_variable: It is the address of another variable.

Example:
int a; int a;
int *ptr; or int *ptr=&a;
ptr=&a;
14.4 Types of Pointer
14.4.1 Null Pointers
✓ Null pointer which is a special pointer value and does
not point to any value.
✓ This means that a null pointer does not point to any
valid memory address.
✓ To declare a null pointer, you may use the predefined
constant NULL which is defined in several standard header
files including <stdio.h>, <stdlib.h> , and <string.h>.
✓ After including any of these files in program, one can
write
int *ptr = NULL;
Uses of NULL Pointer in C

Following are some most common uses of the NULL


pointer in C:
• To initialize a pointer variable when that pointer
variable hasn’t been assigned any valid memory
address yet.
• To check for a null pointer before accessing any
pointer variable. By doing so, we can perform error
handling in pointer-related code, e.g., dereference a
pointer variable only if it’s not NULL.
• To pass a null pointer to a function argument when we
don’t want to pass any valid memory address.
• A NULL pointer is used in data structures like trees,
linked lists, etc. to indicate the end.
• You can always check whether a given pointer variable
stores the address of some variable or contains NULL by
writing,

if (ptr == NULL)
{
Statement block;
}
14.4.2 Generic Pointers
✓ A generic pointer is a pointer variable that has void as
its data type.
✓ The void pointer, or the generic pointer, is a special
type of pointer that can point to variables of any data
type.
✓ It is declared like a normal pointer variable but using
the void keyword as the pointer’s data type.
For example,
void *ptr;
✓ Generic pointers are often used when you want a
pointer to point to data of different types at different
times.
Example:
#include <stdio.h>
void main()
{
int x=10;
char ch = ‘A’;
void *gp;
gp = &x;
printf("\n Generic pointer points to the integer value = %d",
*(int*)gp);
gp = &ch;
printf("\n Generic pointer now points to the character= %c",
*(char*)gp);
}

Output:
Generic pointer points to the integer value = 10
Generic pointer now points to the character = A
14.5 Passing Arguments to Function
Using Pointers

• Call-by-value
• Call by reference
Write a C program to add two numbers using call by
reference
#include<stdio.h>
int add (int *a, int *b)
{
int sum;
sum = *a + *b;
return sum;
}
void main()
{
int a,b, res;
printf(“Enter the values of a and b:”); scanf(“%d%d”,&a,&b);
res = add(&a,&b);
printf(“result =%d\n”, res);
}
To be continued…

You might also like