0% found this document useful (0 votes)
23 views

Unit 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Unit 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Strings in C

Strings
What is string?
• A string is a collection or group of characters
enclosed in double quotes.
• It is also known as an array of characters.
Example: “Hello”, “Belagavi”
• Strings end with a null character (‘\0’)
String Taxonomy or Types of Strings

There are two types of strings:


1. Fixed-length string: is a type of string where length of string
is fixed, length of the string cannot be changed, once defined. For
instance, if you have a large string and you have reserved smaller space
then larger half of string will not be stored. In contrast, if you have a
small string and you have reserved larger space then limited memory is
wasted.

2. Variable length string: is a type of string whose length is


unknown as the name suggests. Storage container contracts and
expands according to requirement of string length. But there has to be
way to indicate the finish signal to compiler and for that purpose we
have two general approaches and they are as follows:
a. Length controlled string: length information
of string is stored as part of string. This
information is stored as first byte and this is
used as a counter.
b. Delimited variable length string: is a type of
string wherein a delimiter (‘\0’) is used at end
the string.
Declaring a String
Syntax of Declaring a string:
char string_name[size];

Example:
char s[10];
10 memory blocks are allocated, each block of one byte size, therefore, total
size is 10 bytes , from the above declaration, as shown below,
S
S[0] S[1] S[2] S[3] S[4] S[5] S[6] S[7] S[8] S[9]
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
Initializing a String
Initializing a String

Compile time initialization Run time initialization

1. char s[6]={ ‘H’, ’E, ’L’, ’L’, ’O’, ’\0’ }; 1. Using scanf()
// Character constant, note in this char s[6];
we need to explicitly specify null scanf(“%s”, s);
character(‘\0’) 2. Using gets()
2. char s[6]=“HELLO”; char s[6];
// String initialization gets(s)
3. char s[ ]=“HELLO”; // Without size

H E L L O \0
S[0] S[1] S[2] S[3] S[4] S[5]
A Simple Program to Scan and Print a string
• Both programs help us to scan and print a string, the only difference is, in first
program scanf() is used and second gets() is used, however both are input functions
which help us to scan a string.
• scanf(): reads input until it encounters whitespace or newline. Once it encounters
any of the two it stops and ends the string there itself with the delimiter.
• gets(): reads a string until it encounters newline, once it encounters newline it
ends the string there itself with the delimiter.
String Handling Functions/String Manipulation Functions

Strings have a very rich built in functions, for processing the


string, which are defined in the header file <string.h>, hence if we
want to use any of the string built in functions we need to include the
header file in our program. Below are few important and basic string
handling functions,
Functions Description
strlen(s) Find the length of the given string
strrev(s) Reverses the given string
strcpy(s1,s2) Copies one string to another string
strcmp(s1,s2) Compares two strings for equality
strcat(s1,s2) Concatenates or Joins two strings
strlwr(s) Converts the given string to lower case string
strupr(s) Converts the given string to uppercase string
String Handling Functions
strlen():- it is used to find the length of the string.
-it returns an integer value.
Syntax: Example:
length=strlen(string); char S[10]=“Hello”;
int length;
length = strlen(S);

Output:
Length=5
String Handling Functions
strrev():- it is used to reverse the given string.
-it returns a string.
Syntax: Example:
strrev(string); char S[10]=“Hello”;
strrev(S);

Output:
Reversed String=olleH
String Handling Functions
strcpy():- it is used to copy one string to another string.
-it returns a string.
Syntax: Example:
strcpy(destination_str, source_str); char S1[10]=“Hello”;
char S2[10];
strcpy(S2,S1);

Output:
Copied String=Hello
String Handling Functions
strcat():- it is used to join or concatenate two strings.
-it returns concatenated/joined string.
Syntax: Example:
strcat(string1, string2); char S1[10]=“Hello”;
char S2[10]=“All”;
strcat(S1,S2);

Output:
Joined String=HelloAll
String Handling Functions
strcmp(): -it is used to compare two strings for equality.
-it returns zero if both strings are same.
Syntax: Example:
strcmp(string1, string2); char S1[10]=“Hello”;
char S2[10]=“Hello”;
strcmp(S1,S2);

Output:
Strings are same
String Handling Functions
strlwr(): -it is used to change case of string to lower case.
strupr(): -it is used to change case of string to upper case.
Syntax: Example:
strlwr(string); strupr(string); char S[10]=“hello”;
strupr(S);
strlwr(S);

Output:
String=HELLO
String=hello
Programs on
Strings
Program for finding Length of a given string
Consider a string S char S[10]=“HELLO”
H E L L O \0
Let Initially COUNT=0 S[0] S[1] S[2] S[3] S[4] S[5]
YES
Is S[0]!=‘\0’ ? Its ‘H’ Not Null character So, COUNT=1

YES
Is S[1]!=‘\0’ ? Its ‘E’ Not Null character So, COUNT=2

Is S[2]!=‘\0’ ? YES
Its ‘L’ Not Null character So, COUNT=3

Is S[3]!=‘\0’ ? YES
Its ‘L’ Not Null character So, COUNT=4

Is S[4]!=‘\0’ ? YES
Its ‘0’ Not Null character So, COUNT=5

NO
Is S[5]!=‘\0’ ?
Its ‘\0’ Null character
Therefore in general,
for(i=0;s[i]!=‘\0’;i++)
count=count+1
Write a C program to read a string and find the length of the string without
using built-in function

Program:
Program to copy one string to another string
Consider two strings string S1 and string S2, char S1[10]=“HELLO”

S2[0] = S1[0]
H E L L O \0
S2[1] = S1[1] S1[0] S1[1] S1[2] S1[3] S1[4] S1[5]

S2[2] = S1[2]

S2[3] = S1[3] H E L L O
S2[0] S2[1] S2[2] S2[3] S2[4] S2[5]
S2[4] = S1[4]

Therefore in general,
for( i=0; S1[i]!=‘\0’ ; i++)
S2[ i ] = S1[ i ]
S2[ i ]=‘\0’
Write a C program to read a string s1 and copy its content to another string s2
without using built-in function

Program:

Output:
Program for concatenating two strings:
Consider two strings string S1 and string S2
Length of S1 ?
char S1[10]=“HELLO” and char s2[10]=“ALL”
To join to its end…!!!!

H E L L O \0
A L L
S1[0] S1[1] S1[2] S1[3] S1[4] S1[5] S1[6] S1[7] S1[8]

A L L \0
S2[0] S2[1] S2[2] S2[3] S2[4] S2[5]
Therefore in general,
S1[5] = S2[0] for(i=0;s[i]!=‘\0’;i++)
count=count+1
S1[6] = S2[1] for( i=0; S2[i]!=‘\0’ ; i++,count++)
S1[ count ] = S2[ i ]
S1[7] = S2[2]
S1[ count ]= ‘\0’
Write a C program to read two strings s1 and s2 and then concatenate both
strings without using built-in function

Program:
Write a C program to read a string s and then reverse it without using built-in function

Program:

Output:
Write a C program to read a string s and then reverse it without using built-in function

Program:

Output:
Write a program to read a sentence and count the frequency of the given
character in the sentence.
Write a program to read a sentence and count the frequency of each vowel in it.

OR
Write a program to read a sentence and count the number of words in it.
Write a program to read a sentence and count the number of characters, words,
and spaces in it.
Arrays of Strings

• An array of strings in C is a two-dimensional


array of character types. Each String is
terminated with a null character (\0). It is an
application of a 2d array.

• When we assign the number of rows and columns, we need


to consider the Null Character to the length.
Arrays of Strings

• char Array[3][6] = {"Black", "Blame", "Black"} -> {{'B', 'l',


'a', 'c', 'k', '\0'}, {'B', 'l', 'a', 'm', 'e', '\0'}, {'B', 'l', 'a', 'c', 'k', '\
0'}}
• We cannot directly manipulate the Strings in the Array as
a String is an immutable data type. The compiler raises an
error:
String and Character Functions
Reading Strings
• The ways to read a string
char str[100];
1. Using scanf() function
• The syntax is
scanf(“%s”, str);
• Unlike integer, float and char, %s format does not require the &
before the variable str.
• Null character is appended automatically at the end of the string
• The drawback with the scanf() function is that it terminates as
soon as it finds a blank space
2. Using gets() function
• The syntax is
gets(str);
• It overcomes the drawbacks of the scanf() function
• It takes the starting address of the string which will hold
the input
• The string will then be automatically terminated with a null
character
3. Using getchar(), getch() or getche function
char ch;
• The syntax is
getchar(ch);
• It reads a single character.
• It can be called repeatedly to read a sequence of single
characters (until a terminating character is entered)
• In this method, null character must be appended manually
at the end of the sequence
Writing Strings
• Ways to display/write a string on the screen
1. Using printf() function
• The syntax is
printf(“%s”, str);
2. Using puts() function
• The syntax is
puts(str);
• It terminates the line with a newline character (‘\n’)
which was not done by printf() function
Pointers
Introduction
• A pointer is a derived type in C that contains
memory address as its value.
• Pointers can be used to return multiple values
from a function via function arguments (output
parameters).
• Pointers allow C to support dynamic memory
management.
• Use of pointers increases the execution speed
and thus reduces the program execution time.
Understanding Pointers
0
• Computer’s memory is a sequential 1
collection of storage location. 2
• Each location, commonly known as 3

a byte, is identified by an address 4


5
associated with it.
.
• These addresses are numbered .
consecutively, starting from zero. .

• The last address depends on the .

memory size.
– A computer system having 64K
memory has its last address as 65535. 65535
• int quantity = 250;
quantity variable

250 value

5000 address

• A variable that can hold address of another


variable is called a pointer variable.
• int quantity = 250;
• int *p = &quantity;

variable value address


quantity 250 5000

p 5000 5012
• Since the value of the variable p is the address of the variable
quantity, we may access the value of quantity by using the
variable p, and therefore we say that the variable p points to
the variable quantity. Thus p is the name of the pointer.
Accessing the Address of a Variable
• We can access the address of a variable with
the & operator in C.
– We have already used & operator in scanf function.
• The operator & immediately preceding the
variable returns the address of the variable
associated with it.
– p = &quantity; //assigns the address 5000 to p.
• The & operator can be used only with a simple
variable or an array element.
main()
{
int a;
float p, q;
char choice;
a = 15;
p = 10.25f;
q = 5.46f;
choice = 'Y';
printf("%d is stored at address %u\n", a, &a);
printf("%f is stored at address %u\n", p, &p);
printf("%f is stored at address %u\n", q, &q);
printf("%c is stored at address %u\n", choice, &choice);
}
Output:
15 is stored at address 6356748
10.250000 is stored at address 6356744
5.460000 is stored at address 6356740
Y is stored at address 6356739
Declaring Pointer Variables
• datatype *ptr_name;
– The asterix (*) tells that the variable ptr_name is a pointer variable.
– ptr_name needs a memory location.
– ptr_name points to a variable of type data_type.
• int *p; // declares the variable p as a pointer variable that can point to an
// integer data type.
• float *q; // declares the variable q as a pointer variable that can point to
// an float data type.
• Since the memory locations corresponding to p and q have not been
assigned any values, these contain garbage value and therefore point to
unknown locations.
– Example: int *p;

p ? ?
contains points to
garbage unknown location
Initialization of Pointer Variable
• The process of assigning the address of a
variable to a pointer variable is known as
initialization.
– Uninitialized pointers will have unknown values.
– It is important to initialize pointer variables before
they are used in the program.
• int quantity;
• int *p;
• p = &quantity; int *p = &quantity;
Initialization of Pointer Variable
• We must ensure that the pointer variables always point to the
corresponding type of data.
– float a, b;
– int sum, *p;
– p = &a; // Wrong
• It is possible to declare combine declaration of simple variable,
declaration and initialization pointer variable in one statement.
– int a, *p = &a;
– Declares a as an integer variable and p as a pointer variable and then
initializes p to address of a.
• We can also define a pointer variable with an initial value of NULL or
zero.
– int *p = NULL; // same as int *p = 0;
Accessing a Variable Through its Pointer
• To access value of a variable using the pointer,
we use the asterisk (*) operator, also known as
the indirection operator or dereferencing
operator.
– int quantity, *p, n;
– quantity = 250;
– p = &quantity;
– n = *p; // equivalent to n = *&quantity; which in turn
// is equivalent to n = quantity;
– Here *p returns the value of the variable quantity.
main()
{
int a, b;
int *p;
a = 15;
p = &a;
b = *p;
printf("Value of a is %d and address is %u\n", a, &a);
printf("Value of a is %d and address is %u\n", *&a, &a);
printf("Value of a is %d and address is %u\n", *p, p);
printf("%d is the address pointed to by %u\n", p, &p);
printf("Value of b is %d and address is %u\n", b, &b);
*p = 25;
printf("Now the value of a is %d", a);
}
Value of a is 15 and address is 6356748
Value of a is 15 and address is 6356748
Value of a is 15 and address is 6356748
6356748 is the address pointed to by 6356740
Value of b is 15 and address is 6356744
Now the value of a is 25
Stage Values stored in locations and their addresses
a b p

Declaration

6356748 6356744 6356740


a b p

a = 10 10

6356748 6356744 6356740


a b p

p = &a 10 6356748

6356748 6356744 6356740


a b p

b = *p 10 10 6356748

6356748 6356744 6356740


a b p

b = *p 10 10 6356748

6356748 6356744 6356740


Call by Value/ Pass by Value

OUTPUT
Call by Reference/ Pass by Reference

OUTPUT

You might also like