0% found this document useful (0 votes)
34 views31 pages

Strings: Divyashikha Sethia (DTU) Divyashikha@dtu - Ac.in

The document discusses strings in C programming. It contains the following key points: 1. Strings in C are null-terminated character arrays that store characters and a null character. 2. Common string operations include finding length, converting case, appending, comparing, reversing, and manipulating substrings. 3. Functions like strlen(), strcat(), strcmp() can be used to perform various string operations in C. Arrays, loops and conditionals can also be used to manually implement string functions.

Uploaded by

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

Strings: Divyashikha Sethia (DTU) Divyashikha@dtu - Ac.in

The document discusses strings in C programming. It contains the following key points: 1. Strings in C are null-terminated character arrays that store characters and a null character. 2. Common string operations include finding length, converting case, appending, comparing, reversing, and manipulating substrings. 3. Functions like strlen(), strcat(), strcmp() can be used to perform various string operations in C. Arrays, loops and conditionals can also be used to manually implement string functions.

Uploaded by

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

STRINGS

Divyashikha Sethia
(DTU)
[email protected]
4.1 STRINGS
•In C, a string is a null-terminated character array.
•After the last character, a null character ('\0') is stored to
signify the end of the character array.
Following is an example of declaring an array that has
five characters,
char str[] = "HELLO";

•Apart from these characters, a null character ('\0') is


stored at the end of the string.
•Internal representation of the string: HELLO'\0'.
•To store a string of length 5, require 5 + 1 locations (1
extra for the null character).

2
STORAGE
Name of character array (or the string): pointer to the
beginning of the string.

3
ACCESS TO
CHARACTERS
•Similar to subscripts/index to
access the elements of an array,
use subscripts to
access the elements of a string.
•Start subscript: 0 All the characters
of a string are stored in successive
memory locations.
•String is a sequence of characters.
•Character H is stored at memory
location 1000 but in reality, the
ASCII code of a character is stored
in the memory and not the
character itself. 4
DECLARATIONS
Constant string
char str[] = "HELLO";

It declares a constant string, as we have assigned a


value to it while declaring the string.

•Initialization with size equal to number of characters.


char str[5] = "HELLO";
Here null character will not be appended automatically to
the character array because string can hold only 5
characters and the characters in HELLO have already
filled the space allocated.
5
DECLARATIONS
• General form of declaration
char str[size];

When we declare the string like this, we can store size–1


characters in the array because the last character would be the
null character. For example, char message[100];can store a
maximum of 99 characters.
• Initialize as array of characters
char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};

In this example, we have explicitly added the null character.


Here, the compiler will automatically calculate the size based
on the number of characters. So, in this example six memory
locations will be reserved to store the string variable, str.
6
DECLARATIONS
Size larger than string length
char str [10] = "HELLO";

In such cases, the compiler creates an array of size 10; stores


"HELLO" in it and finally terminates the string with a null
character. Rest of the elements in the array are automatically
initialized to NULL.

Illegal declaration
char str[3];
str = "HELLO";

The above initialization statement is illegal in C and would


generate a compile-time error because of two reasons. First, the
array is initialized with more elements than it can store. Second,
initialization cannot be separated from declaration. 7
4.1.1 READING STRINGS
To read a string e.g. ,
char str[100];
we can use the following methods –
• scanf() function
scanf("%s", str);

=> The main pitfall using this function is that the function terminates as
soon as it finds a blank space. For example, if the user enters Hello
World, then the str will contain only Hello .

•gets() function
gets(str);

The gets() function takes the starting address of the string which will
hold the input. The string inputted using gets() is automatically
terminated with a null character. It doesn‟t suffer from the drawback of
8
scanf() function
READING STRINGS
•getchar()/getch()/getche() function
Strings can also be read by calling the getchar() function
repeatedly to read a sequence of single characters
(unless a terminating character is entered) and
simultaneously storing it in a character array as shown
below.
i=0;()
ch = getchar();// Get a character
while(ch != '*') // ‘*’ is the terminating character here
{
str[i] = ch;// Store the read character in str i++;
ch = getchar();// Get another character
}
str[i] = '\0';// Terminate str with null character

Note that in this method, you have to deliberately append


the string with a null character. The other two functions
automatically do this. 9
4.1.2 WRITING STRINGS
To write a string to the screen, we can use the following methods -
•printf() function
printf("%s", str);

We may also use width and precision specifications along with %s.
The width specifies the minimum output field width. If the string is
short, the extra space is either left padded or right padded. A
negative width left pads short string rather than the default right
justification.

The precision specifies the maximum number of characters to be


displayed, after which the string is truncated.
printf ("%-5.3s", str);

The above statement would print only the first three characters in a
total field of five characters. Also these characters would be right
justified in the allocated width. To make the stringleft justified, we
10
must use a minus sign.
WRITING STRINGS
puts() function
puts(str);

• puts() is a simple function that overcomes the


drawbacks of the printf() function.
•putchar() function
• Strings can also be written by calling the putchar()
function repeatedly to print a sequence of single
characters .
i=0;
while(str[i] != '\0')
{

putchar(str[i]);// Print the character on the screen i++;


}

11
4.2 OPERATION ON
STRINGS
•Finding Length of a String
•Converting Characters of a String into Upper/ Lower
Case
•Appending a String to Another String
•Comparing Two Strings
•Reversing a String
•Extracting a Substring from a String
•Inserting a String in the Main String
•Pattern Matching
•Deleting a Substring from the Main String
•Replacing a Pattern with Another Pattern in a String 12
LENGTH OF 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.
•In the algorithm, Iis used as an index
for traversing string STR. To traverse
each and every character of STR, we
increment the value ofI.
•Once we encounter the null character,
the control jumps out of the while loop
and the length is initialized with the
value ofI.
•The library functions trlen(s1) which
is defined in
• string.hreturns the length of string 13
s1.
STRING TO
UPPERCASE/LOWERCASE
•The ASCII code forA–Zvaries from 65 to 91 and the ASCII
code fora–zranges 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. And if we have to convert character into lower
• case, we need to add 32 to the ASCII value.
•In the algorithm, using Ias the index of STR, we traverse
each character of STR from Step 2 to 3.
•If the character is in lower case, then it is converted into
• upper case by subtracting 32 from its ASCII value.
Otherwise, it is copied into the UPPER STRstring.
•Finally, when all the characters have been traversed, a null
character is appended toUPPER STR.
•The library functionstoupper()andtolower()which are defined
inctype.hconvert a character into upper and lower case,
14
respectively.
APPENDING ONE STRING
TO ANOTHER
•Appending one string to another string involves copying the contents of
the source string at the end of the destination string.
•So, if S1 is the source string and S2 is the destination string, then
appending operation would leave the source string S1 unchanged and
the destination string S2 = S2 + S1.
•The library function strcat(s1, s2)which is defined in string.h
concatenates string s2 to s1.
•In the algorithm, we first traverse through
the destination string to reach its end.
•The characters of the source string are then
copied into the destination string starting
from that position.
•Finally, a null character is added to
terminate the destination string.
15
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, when in dictionary order, S1 will come after S2
•(c) S1<S2, when in dictionary order, S1 precedes S2

•To compare the two strings, each and every character is


compared from both the strings.
•If all the characters are the same, then the two strings are said
to be equal.
•The library function strcmp(s1, s2)which is defined in string.h
compares string s1 with s2. 16
COMPARING TWO STRINGS
•In this algorithm, we first check
whether the two strings are of the
same length.
•If not, then there is no point in moving
ahead, as it straight away means that
the two strings are not the same.
•However, if the two strings are of the
same length, then we compare
character by character to check
•if all the characters are same. If yes,
then the
• Variable SAME is set to 1.
•Else, if SAME = 0, then we check
which string precedes the other in the
dictionary order and print the
corresponding message. 17
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.

•In Step 2, a while loop is executed until all the characters of the
string are accessed.
•In Step 3, we swap the ith character of STR with its jth character.
As a result, the first character of STR will be replaced with its
last character, the second character will be replaced with the
second last character of STR, and so on.
•In Step 4, the value of I is incremented and J is decremented to
traverse STR in the forward and backward directions,18
respectively.
EXTRACTING SUBSTRING
FROM A STRING
•To extract a substring from a given string, we need the
following three parameters:
1. the main string,
2. the position of the first character of the substring in
the given string, and
3. the maximum number of characters/length of the
substring.
•For example, if we have a string
str[] = "Welcome to the world of programming";
•Then, result should be :
SUBSTRING(str, 15, 5) = world
19
EXTRACTING SUBSTRING
FROM A STRING
•In this algorithm, we initialize a
loop counter Ito M, that is, the
position from which the characters
have to be copied.
•Steps 3 to 6 are repeated until N
characters have been copied.
•With every character copied, we
decrement the value of N.
•The characters of the string are copied into
another string called the SUBSTR.
•At the end, a null character is appended to
SUBSTR to terminate the string.
20
INSERTING A STRING IN MAIN STRING
•The insertion operation inserts a string S in
the main text T at the kth position.
•The general syntax of this operation is
I NSERT(text, position, string).
For example, INSERT("XYZXYZ", 3,
"AAA")="XYZAAAXYZ"
•The algorithm first initializes the indices into
the string to zero.
•From Steps 3 to 5, the contents
ofNEW_STRare built.
•IfIis exactly equal to the position at which the
substring has to be inserted, then the inner
loop copies the contents of the substring into
NEW_STR.
•Otherwise, the contents of the text are copied
into it.

21
PATTERN MATCHING
•This operation returns
the position in the string
where the string pattern
first occurs. For
example,
char str[] = "Welcome to the world of
programming";
char pattern[] = "world";
INDEX(str, pattern); // = 15

•However, if the pattern does not


exist in the string, the INDEX
function returns 0.

22
PATTERN MATCHING
•Inthis algorithm, MAX is
initialized to
• length(TEXT)–Length(STR) + 1.
•For example, if a text contains 'Welcome
To Programming‘ and the string contains‘
World', in the main text, we will look for at
the most 22–5
• + 1 = 18 characters because after that
there is no scope left for the string to be
present in the text.
•In the inner loop in Step 3, we check the n
characters of string with the n characters of
text to find if the characters are same.
•If it is not the case, then we move to
Step 6,
• where I is incremented.

23
PATTERN MATCHING
•If the string is found, then the index
is initialized with I, else it is set to–
1.
•For example, if
•TEXT =“WELCOMETO THEWORLD”
•STRING =“COME”
•In the first pass of the inner loop,
we will compare “COME” with
“WELC” character by character.
•As„W‟and„C‟do not match, the
control will move to Step 6 and
then “ELCO” will be compared with
“COME”. In the fourth pass,
“COME”will be compared with
“COME”.

24
DELETING A SUBSTRING
FROM MAIN STRING
The replacement operation is used to replace the pattern P1
by another pattern P2.
Syntax : REPLACE(text, pattern1, pattern2)

For example,
REPLACE("AAABBBCCC", "BBB", "X"); // = AAAXCCC
REPLACE("AAABBBCCC", "X", "YYY"); // = AAABBBCC , no change since pattern 1 not found in text.

•In the algorithm, we first find the position POS, at which the
pattern occurs in the text.
•Then delete the existing pattern from that position and insert
a new pattern there.

25
REPLACING A PATTERN WITH
ANOTHER PATTERN IN THE
STRING
•The replacement operation is used to replace the pattern P1
by another pattern P2.
Syntax : REPLACE(text, pattern1, pattern2)

For example,
REPLACE("AAABBBCCC", "BBB", "X"); // = AAAXCCC
REPLACE("AAABBBCCC", "X", "YYY"); // = AAABBBCC , no change since pattern 1 not found in
text.

•In the algorithm, we first find the position POS, at which the
pattern occurs in the text.
•Then delete the existing pattern from that position and insert
a new pattern there.
26
4.3 ARRAY OF STRINGS
An array of strings is declared as
char names[20][30]; // names of 20 students in a class

• Here, the first index will specify how many strings are
needed and the second index will specify the length of every
individual string. So here, we will allocate space for 20 names
where each name can be a maximum 30 characters long.
• If we have an array declared as
char name[5][10] = {"Ram", "Mohan", "Shyam", "Hari", "Gopal"};

Then in the memory, the array will be stored as

27
ARRAY OF STRINGS
By declaring the array names
char name[5][10] = {"Ram", "Mohan", "Shyam", "Hari", "Gopal"}; // 4 + 6 + 6 + 5 + 6 = 27 bytes

we allocate 50 bytes. But the actual memory occupied is 27


bytes. Thus, we see that about half of the memory allocated is
wasted.
To process individual string from an array of strings, we use
following algorithm

In Step 1, we initialize the index variable I to zero. In Step 2, a


while loop is executed until all the strings in the array are
accessed. In Step 3, each individual string is processed.
28
4.4 POINTERS AND
STRINGS
• In C, strings are treated as arrays of characters that are terminated
with a binary zero character (written as '\0').
• Like for an array , we can also process characters of a string using
character pointer.

In this program, we declare a character pointer


*pstr to show the string on the screen.

We then point the pointer pstr to str. Then, we


print each character of the string using the
while loop.

29
POINTERS AND STRINGS
• Instead of using the while loop, we could straightaway use the
function puts(), as shown below
puts(pstr);

The function prototype for puts() is as follows:


int puts(const char *s);

• Here the constmodifier is used to assure that the function dose


not modify the contents pointed to by the source pointer. The
address of the string is passed to the function as an argument.
• The parameter passed to puts()is a pointer which is nothing
but the address to which it points to or simply an address. Thus,
writing puts(str)means passing the address of str[0]. Similarly
when we write puts(pstr);we are passing the same address,
because we have written pstr = str;.
30
THANKS

31

You might also like