Chp3 Strings
Chp3 Strings
CHAPTER 3
INTRODUCTION TO STRINGS
• VARIABLES
• CONSTANTS
Character variables fall into three categories
• Many programming languages denote
• By a static character variable, we mean a variable
string constants by placing the string in
whose length is defined before the program is executed
either single or double quotation marks. and cannot change throughout the program.
For example, 'THE END' and ‘TO BE
• By a semistatic character variable, we mean a variable
OR NOT TO BE’ are string constants of whose length may vary during the execution of the
lengths 7 and 18 characters respectively. program as long as the length does not exceed a
• . maximum value determined by the program before the
program is executed.
• By a dynamic character variable, we mean a variable
whose length can change during the execution of the
program
STRING OPERATIONS
• Indexing, also called pattern matching, refers to finding the position where a string
pattern P first appears in a given string text T.
• We call this operation INDEX and write INDEX(text, pattern).
• If the pattern P does not appear in the text T, then INDEX is assigned the value 0.
strcpy(s1, s2);
1
Copies string s2 into string s1.
strcat(s1, s2);
2
Concatenates string s2 onto the end of string s1.
strlen(s1);
3
Returns the length of string s1.
strcmp(s1, s2);
4 Returns 0 if s1 and s2 are the same; less than 0 if
s1<s2; greater than 0 if s1>s2.
strchr(s1, ch);
5 Returns a pointer to the first occurrence of
character ch in string s1.
strstr(s1, s2);
6 Returns a pointer to the first occurrence of string
s2 in string s1.
3.CONCATENATION
• The strcmp() function in C++ compares two null-terminating strings (C-strings). The
comparison is done lexicographically. It is defined in the cstring header file.
• char str1[] = "Megadeth";
• char str2[] = "Metallica";
• int result = strcmp(str1, str2);
SUBSTRING
4.LENGTH
• The following operations can be executed by using the string operations discussed in the
preceding section
(a) Replacement. Replacing one string in the text by another.
(b) Insertion. Inserting a string in the middle of the text.
(c) Deletion. Deleting a string from the text.
INSERTION
• Suppose in a given text T we want to delete the substring which begins in position K and
has length L. We denote this operation by DELETE(text, position, length)
• DELETE(' ABCDEFG ', 4, 2) = ' ABCFG ‘
• DELETE(' ABCDEFG ', 2, 4) = ' AFG ‘
• We assume that nothing is deleted if position K = 0. Thus DELETE(' ABCDEFG ', 0, 2)
= ' ABCDEFG '
REPLACEMENT