Pds PB 2019 Strings

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

Plan Comp Str Data Opr Expr/Stmt Iter int float Functions Characters & Strings Searching Structu

Programming and Data Structure


CS 11002

Prof. Partha Bhowmick


http://cse.iitkgp.ac.in/~pb
Computer Science and Engineering Department
IIT Kharagpur

Spring 2018-2019

PB | CSE IITKGP | Spring 2018-2019 PDS


Characters
& Strings
Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String (1)

Day 8 • Lecture 12 • 05-Feb-2019

A string of characters is a sequence of data of


type char (ASCII codes) stored in a 1-D array
comprising consecutive memory locations and
terminated by the NULL character (\0 of ASCII
value = 0).
A string constant is written within a pair of
double quotes, e.g., "IIT Kharagpur".
0 13
I I T K h a r a g p u r \0 · · ·
73 73 84 32 ··· 0 ···

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

1-D Array (1)

#include <stdio.h>
int main(){ // finds the largest element
int a[100], n, i;
printf("Enter number of elements (at most 100): ");
scanf("%d", &n);
printf("Enter the elements: ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
max = a[0];
for(i=1; i<n; i++)
if(a[i]>max) max = a[i];
printf("Largest element = %d.\n", max);
return 1;
}

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

1-D Array (2)

Similarly, we can declare one-dimensional array of


any other data type, e.g., float, double, etc.

We can also declare arrays of user-defined data


types, e.g., array of 2D points, array of 3D
points, ..., array of complex numbers, array of
structured data like employee records, customer
records, student records, etc.

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Initialization of a String (1)

#include <stdio.h>
#define MAXLEN 100
int main(){ // stringInit.c
char a[MAXLEN]={’B’,’i’,’g’,’ ’,
’B’,’a’,’n’,’g’,’\0’},
b[MAXLEN]="Black Hole",
c[]="Quantum Gravity",
*cP="Super String";
printf("a: %s\nb: %s\nc: %s\n*cP: %s\n",
a, b, c, cP);
printf("a[0]=%c, b[1]=%c, c[2]=%c, cP[3]=%c\n",
a[0], b[1], c[2], cP[3]);
return 0;}

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Initialization of a String (2)

$cc -Wall stringInit.c


$a.out
a: Big Bang
b: Black Hole
c: Quantum Gravity
*cP: Super String
a[0]=B, b[1]=l, c[2]=a, cP[3]=e

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Initialization of a String (3)

Note
Space is allocated in main memory for a[],
b[], c[] to store the strings.
The constant string pointed by cP is stored
in the read-only segment of main memory.
The pointer cP directly points to the
beginning of that string in the memory. Any
attempt to change that location results in
segmentation violation in GCC.
(See stringInit1.c in the next slide.)

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Initialization of a String (4)

#include <stdio.h>
#define MAXLEN 100
int main(){ // stringInit1.c
char a[MAXLEN]={’B’,’i’,’g’,’ ’,
’B’,’a’,’n’,’g’,’\0’},
b[MAXLEN]="Black Hole",
c[]="Quantum Gravity",
*cP="Super String";
a[0] = ’b’, b[0] = ’b’, c[0] = ’q’; // OK
cP[0] = ’A’; // segmentation fault
return 0;}

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Reading a String (1)

The library function scanf() can be used to read


a string. The format specifier for a sequence of
non-white-space characters is %s.

#include <stdio.h>
#define MAXLEN 100
int main(){ // stringRead1.c
char a[MAXLEN], b[MAXLEN], c[MAXLEN];
printf("Enter the 1st string: ");
scanf("%s",a); printf("a: %s\n",a);
printf("Enter the 2nd string: ");
//read all characters until \n (or EOF)
scanf("%[^\n]",b); printf("b: %s\n",b);

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Reading a String (2)

printf("Enter the 3rd string: ");


scanf(" %[^\n]",c); printf("c: %s\n",c);
return 0;}

$cc -Wall stringRead1.c


$a.out
Enter the 1st string: The world is made of facts
a: The
Enter the 2nd string of char
b: world is made of facts
Enter the 3rd string of char
and not of matter.
c: and not of matter.

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Length (1)

Write a non-recursive function that will take a


character string as a parameter and will return
its length.
Also write a recursive function to do the same
job.

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Length (2)

Non-recursive Function

int length(char *s) {


int len=0;
while(s[len]) ++len;
return len;
} // lengthI.c

Note: The while loop terminates if s[len]


contains \0 (ASCII value is zero).

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Length (3)

Recursive Definition


0 if s = NULL,
length(s) =
1 + length(tail(s)) otherwise.

where tail(s) is the string after removal of the 0th


character of s.

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Length (4)

Recursive Function

#define NULL (’\0’)


int length(char *s){//s is a pointer to char
if(s[0] == NULL) return 0;
return 1 + length(s+1);
} // lengthR.c
...
s s+1 s+2

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Length (5)

The function size t strlen(const char *s)


returns the length of the string.
Note
string.h is the header file that contains the
library functions to manipulate strings.
The null character (\0) is not counted.
The character string pointed by s cannot be
changed, as it is const.

To learn more, type on the terminal: man strlen.


To see your computer’s manual on a library function, you should type:
man <function name>.
PB | CSE IITKGP | Spring 2018-2019 PDS
Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Length (6)

#include <stdio.h>
#include <string.h>
#define MAXLEN 100
int length(char *);
int main(){ // lengthL.c
char b[MAXLEN];
printf("Enter a string of char\n");
scanf("%[^\n]", b);
printf("length(%s) = %d\n",b,strlen(b));
return 0;}

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Copy (1)

Day 9 • Lecture 13 • 08-Feb-2019

Write a non-recursive and a recursive program to


copy a string to another array.
Assume that the target array has sufficient space.
The function should return the number of
characters copied.

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Copy (2)

Non-recursive Function
#define NULL (’\0’)
int strCopy(char *dst, const char *src){
int count=-1;
do{
++count;
dst[count] = src[count];
} while(src[count] != NULL);
return count;
} // stringCopyI.c

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Copy (3)

Recursive Function
#define NULL (’\0’)
int strCopy(char *dst, const char *src){
dst[0] = src[0];
if(src[0] == NULL) return 0;
return strCopy(dst+1, src+1) + 1;
} // stringCopyR.c

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Copy (4)

The library function char *strcpy(char *dest,


const char *src) copies the source string to
the destination string. It also returns the
destination string pointer.
Example
strcpy(mycity, "Calcutta");
strcpy(city, mycity);

mycity = "Calcutta"; is an invalid assignment, since assignment op-


erator does not work for strings.

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Concatenation (1)

Write a non-recursive C Function that will


concatenate a string to the end of another string.

Example
Let s="IIT", t="Kharagpur".
After concatenation, s="IITKharagpur".

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Concatenation (2)

Non-recursive Function
#define NULL (’\0’)
int concat(char *dst, const char *sec){
int count=0, i=0;
while(dst[count] != NULL) ++count;
do dst[count++] = sec[i];
while(sec[i++] != NULL);
return count-1;
} // concatI.c

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Concatenation (3)

The library function char *strcat(char *dest,


const char *src) concatenates the source
string to the destination string.
It also returns the destination string pointer.

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Comparison (1)

Write a non-recursive and a recursive C Function


to compare two strings s1 and s2.
They should return < 0 if s1 < s2, 0 if s1 = s2,
or > 0 if s1 > s2.

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Comparison (2)

Non-recursive Function
#define NULL (’\0’)
int strComp(const char *s1, const char *s2){
int i=0;
while(s1[i]==s2[i]
&& s1[i] != NULL
&& s2[i] != NULL) ++i;
if(s1[i] == s2[i]) return 0;
return (int)(s1[i] - s2[i]);
} // strCompI.c

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Prefix (1)

Pattern
A pattern p[0 · · · m − 1] is a prefix of a text
t[0 · · · n − 1] if m 6 n and p[0 · · · m − 1] is same
as t[0 · · · m − 1].

Example
"I" or "II" or "IIT" or "IIT " or "IIT K" or ...
is a prefix of "IIT Kanpur", but "IIIT" is not.
Write a non-recursive and a recursive C Function
to test whether a pattern string is the prefix of a
text string.
PB | CSE IITKGP | Spring 2018-2019 PDS
Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Prefix (2)

Inductive definition


 True, if p = NULL
 False, if p 6= NULL and t = NULL


prefix(p, t) = False, if head(p) 6= head(t)
prefix(tail(p), tail(t)),




 if head(p) = head(t)

where tail(s) is the string after removal of the 0th


character of s.

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Prefix (3)

Non-recursive Function
#define TRUE 1
#define FALSE 0
static int length(const char *);
int isPrefix(const char *t, const char *p) {
int m = length(p), n = length(t), i;
if(m > n) return FALSE;
for(i=0; i<m; ++i)
if(p[i] != t[i]) return FALSE;
return TRUE;} // isPrefixI.c
static int length(const char *s) {
int len=0;
while(s[len]) ++len;
return len;}

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

String Prefix (4)

Recursive Function
#define TRUE 1
#define FALSE 0
#define NULL (’\0’)
int isPrefix(const char *t,
const char *p) {
if(*p == NULL) return TRUE;
if(*p != *t) return FALSE;
return isPrefix(t+1, p+1);
} // isPrefixR.c

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Substring Matching (1)

Substring
A pattern p[0 · · · m − 1] is a substring of a text
t[0 · · · n − 1] if m 6 n and p[0 · · · m − 1] is same
as t[k · · · k + m − 1] for some k > 0.

Example
"muni" is a substring of "communism" with k = 3.
k
0 1 2 3 4 5 6 7 8
c o m m u n i s m

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Substring Matching (2)

Write a non-recursive C Function that tests


whether a pattern string is a substring of a text
string. The function returns −1 if the pattern is
not a substring, otherwise it returns the index of
the starting position (first occurrence) of the
pattern in the text.
Similarly write a recursive C function.

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Substring Matching (3)

Non-recursive Function
#define NULL (’\0’)
int isSubString(const char *t, const char *p){
int index = 0; const char *pP, *tP;
while (*t != NULL) { //p cannot be a substring
tP = t; pP = p;
do {
if(*pP == NULL) return index; //p is a substring
if(*tP == NULL) return -1; //p not a substring
} while (*pP++ == *tP++); //test next character
++index; ++t; } //end while
return NOTSUBSTR;} //subStringI.c

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Substring Matching (4)

Recursive Function
#define NULL (’\0’)
#define TRUE 1
#define FALSE 0
int isSubString(const char *t, const char *p){
int n;
if(length(t) < length(p)) return -1;
if(isPrefix(t, p)) return 0;
n = isSubString(t+1, p);
if(n == -1) return -1;
else return n + 1;} // subStringR.c

PB | CSE IITKGP | Spring 2018-2019 PDS


Plan Comp Str Data Opr Expr/Stmt Iter int floatarray
Functions
init scan
Characters
length &
copy
Strings
compare
Searching
prefixStructu
substr

Substring Matching (5)

The library function char *strstr(const char


*t, const char *p) finds the first occurrence of
the substring p in the string t.

PB | CSE IITKGP | Spring 2018-2019 PDS

You might also like