STRINGS For C Programmers

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

Lecture Notes: C, 2013

Pages 18

PROGRAMMING WITH C (EURCS 105)

Puppetting On Strings
P.Pavan Kumar
Assistant Professor,
Department of Computer Science and Engineering,
GITAM University ,
Hyderabad Campus
Edited on 28/10/2013; Uploaded on 1/11/2013;

GITAM University, Hyderabad(HTP) Campus.

OBJECTIVE
Motivation:
The programming languages have become increasingly important
with the advancement of computer technology. It is essential to write
efficient programs in order to handle a large amount of data. Effiecient
high-level languages like C in conjunction with powerful computers
have helped in solving large and complex problems in reasonable
time.
Targetted People:
This article targetted at the students of science and engineering,
particularly the undergraduate students of circuital(CSE, IT, EEE,
ECE,EIE), non-circuital(Mechanical, Civil, Aeronautical) branches
and those who are interested in learning programming with c.
Learning Objective:
In this article, we will read about array of characters commonly known
as strings. we will see how strings are stored, declared, initialized,
and accessed. we will learn about different operations that can be
performed on strings and learn about array of strings.
Contact:
)
[email protected]

characters in the word Hello.


Syntax of string:
datatype

If we follow the rule of array initialization then we can write the


above statement as follows:
Example-1:
char greeting[6] = {G, I, T, A, M, \0};
(or)
char greeting[ ] = {G, I, T, A, M, \0};
(or)
char greeting[ ] = {GITAM };

Table 1. memory presentation of above-defined string in C

2.1
1

INTRODUCTION

In the prior chapter we learnt how to define arrays of differing


sizes and dimensions, how to initialize arrays, etc.
With this knowledge under your belt, you should be ready to
handle strings, which are, simply put, a special kind of array. And
strings, the ways to manipulate them are going to be the topics of
discussion in this article.

string name[size]={string contents};

\0

What are Strings

The way a group of integers can be stored in an integer array


Similarly a group of characters can be stored in a character array.
Character arrays are many a time also called strings.
Character arrays (or) strings are used by programming
languages to manipulate text such as words and sentences.
A string constant is a one-dimensional array of characters
terminated by a null ( \0 ).

STRINGS

+ The string in C programming language is actually a onedimensional array of characters which is terminated by a null
character \0.
+ Thus a null-terminated string contains the characters that
comprise the string followed by a null. The following declaration
and initialization create a string consisting of the word Hello.
+ To hold the null character at the end of the array, the size of the
character array containing the string is one more than the number of

GITAM UNIVERSITY(HTP Campus) 2013.

Actually, you do not place the null character at the end of a string
constant. The C compiler automatically places the \0 at the end
of the string when it initializes the array. Let us try to print above
mentioned string:

P.Pavan Kumar

1 / W r i t e a program t o d e m o n s t r a t e s t r i n g /
2 # i n c l u d e < s t d i o . h>
3 i n t main ( )
4 {
5 char g r e e t i n g [ 6 ] = { G , I , T , A ,
M , \0 } ;
6 p r i n t f ( G r e e t i n g m e s s a g e : %s \n , g r e e t i n g
);
7 return 0;
8 }

NOTE-I: \0 and 0 are not same. ASCII value of \0 is 0,


whereas ASCII value of 0 is 48.
NOTE-II: The elements of the character array are stored in

string1.c

When the above code is compiled and executed, it produces result


something as follows:
Fig. 1. a character array is stored in memory

OUTPUT:
- Greeting message: GITAM
Example:
My age is 2 (two);
Above statement is a string. The string stored in memory as ASCII
codes of the characters that make up the string, appended with
0(ASCII value of null). Normally, each character is stored in one
byte, and successive characters of the string are stored in successive
bytes.
- NOTE:
Memory presentation of above example string is given in
APPENDIX
1
2
3
3 INITIALIZING STRING
4
Following the discussion on character arrays,(i.e., a string), the 5
initialization of a string must have the following form,(this is similar
to initializing a one dimensional array):
6
EXAMPLE:
7
8
char month1[]={J,A,N,U,A,R,Y,0};
9
10
- Then the the month is initialized to January. This is perfectly
valid, but C offer a special way to initialize strings. the above string 11
12
can be initialized as:
13
(OR)
char month1[]=JANUARY;

contiguous memory locations.


The terminating null (\0 ) is important, because it is the only
way the functions that work with a string can know where the
string ends. In fact, a string not terminated by a \0 is not
really a string, but merely a collection of characters.
C concedes the fact that you would use strings very often and
hence provides a shortcut for initializing strings. For example, the
string used above can also be initialized as,
char name [8] = HAESLER ;
/ Program t o d e m o n s t r a t e p r i n t i n g o f a
s t r i n g /
# i n c l u d e <s t d i o . h>
main ( )
{
char name [ ] = ICFAI F u n d a t i o n f o r H i g h e r
Education ;
int i = 0 ;
w h i l e ( i <= 38 )
{
p r i n t f ( %c , name [ i ] ) ;
i ++ ;
}
p r i n t f ( \n ) ;
}
example11.c

Output
ICFAI Fundation for Higher Education

- The characters of the string are enclosed with pair of double


quotes
1 / Program t o d e m o n s t r a t e p r i n t i n g o f a
string
u s i n g FOR l o o p /
Example:
2 # i n c l u d e <s t d i o . h>
3 main ( )
char name[8] = { H, A, E, S, L, E, R, \0 } ;
4 {
5 char name [ ] = F a c u l t y o f S c i e n c e and
Each character in the array occupies one byte of memory and
Technology ;
the last character is always \0 .
6 int i = 0 ;
What character is this? It looks like two characters, but it is actually 7 f o r ( ; name [ i ] ! = \0 ; i ++)
only one character, with the \indicating that what follows it is 8 {
something special. \0 is called null character.
9 p r i n t f ( %c , name [ i ] ) ;

Puppetting On Strings

10
11
12
13

}
p r i n t f ( \n ) ;
}

1
2
3
4
5

example12.c

Output
Faculty of Science and Technology

6
7

The %s used in printf( ) is a format specification for printing out


8
a string.
The same specification can be used to receive a string from the
keyboard,

str len.c

Output
string = FACULTY OF SCIENCE AND TECHNOLOGY
length = 33

1 / Program t o d e m o n s t r a t e p r i n t i n g o f a
string
( r e c e i v e a s t r i n g from t h e
keyboard ) /
2 # i n c l u d e <s t d i o . h>
3 main ( )
4 {
5 char name [ 2 5 ] ;
6 p r i n t f ( E n t e r y o u r name ) ;
7 s c a n f ( %s , name ) ;
8 p r i n t f ( H e l l o %s ! \ n , name ) ;
9 }

3.1.2

Output
Enter your name: MAHI
Hello MAHI!
RE RUN
Enter your name: mahendra kumar paruchuri
Hello mahendra!

6
7
8
9

RE RUN
10
Enter your name: mahendrakumarpruchuri
Hello mahendrakumarpruchuri!

3.1

Standard Library String Functions

Table 2. Standard Library String Functions

Sr.No.
1.
2.
3.

Function
strlen
strcpy
strcat

4.

strcmp

3.1.1

strlen( )

strcpy( )

+ This function copies the contents of one string into another.


+ The base addresses of the source and target strings should be
supplied to this function.
1
2
3
4
5

example13.c

/ / program t o i l l u s t r a t e STRLEN ( )
# i n c l u d e <s t d i o . h>
main ( )
{
char a r r [ ] = FACULTY OF SCIENCE AND
TECHNOLOGY ;
int len1 ;
len1 = s t r l e n ( arr ) ; / / finding the
l e n g t h o f an a r r a y a r r
p r i n t f ( \ n s t r i n g = %s l e n g t h = %d , a r r ,
len1 ) ;
}

Use
Finds length of a string
Copies a string into another
Appends one string at the end of
another
Compares two strings

1
2
+ This function counts the number of characters present in a string. 3
4

/ / program t o i l l u s t r a t e STRCPY ( )
# i n c l u d e <s t d i o . h>
main ( )
{
char s o u r c e [ 5 0 ] = FACULTY OF SCIENCE AND
TECHNOLOGY ;
char t a r g e t [ 5 0 ] ;
strcpy ( target , source ) ;
p r i n t f ( \ n s o u r c e s t r i n g = %s , s o u r c e ) ;
p r i n t f ( \ n t a r g e t s t r i n g = %s \n , t a r g e t )
;
}
str cpy.c

Output
source string = FACULTY OF SCIENCE AND
TECHNOLOGY
target string = FACULTY OF SCIENCE AND
TECHNOLOGY
3.1.3

strcat( )

+This function concatenates the source string at the end of the


target string.
Example
Bombay and Nagpur on concatenation would result into a
string BombayNagpur .
/ / program t o i l l u s t r a t e STRCAT ( )
# i n c l u d e <s t d i o . h>
main ( )
{

P.Pavan Kumar

5
6
7
8
9
10
11
12
13
14
15
16
17

char word1 [ 3 0 ] ;
char word2 [ 3 0 ] ;
p r i n t f ( E n t e r t h e Word1: ) ;
s c a n f ( %s , word1 ) ;
p r i n t f ( E n t e r t h e Word2: ) ;
s c a n f ( %s , word2 ) ;
p r i n t f ( Before Concatination :\ n ) ;
p r i n t f ( \ nword1 s t r i n g = %s , word1 ) ;
p r i n t f ( \ nword2 s t r i n g = %s \n , word2 ) ;
s t r c a t ( word1 , word2 ) ;
p r i n t f ( After Concatination :\ n ) ;
p r i n t f ( Word1 s t r i n g = %s \n , word1 ) ;
}
str cat.c

Output
Enter the Word-1:andhra
Enter the Word-2:pradesh
Before Concatination:
word-1 string = andhra
word-2 string = pradesh
After Concatination:
Word-1 string = andhrapradesh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/ / program t o i l l u s t r a t e STRCAT ( )
# i n c l u d e <s t d i o . h>
main ( )
{
char word1 [ 3 0 ] ;
char word2 [ 3 0 ] ;
p r i n t f ( E n t e r t h e Word1: ) ;
s c a n f ( %s , word1 ) ;
p r i n t f ( E n t e r t h e Word2: ) ;
s c a n f ( %s , word2 ) ;
p r i n t f ( Before Concatination :\ n ) ;
p r i n t f ( \ nword1 s t r i n g = %s , word1 ) ;
p r i n t f ( \ nword2 s t r i n g = %s \n , word2 ) ;
s t r c a t ( word2 , word1 ) ;
p r i n t f ( After Concatination :\ n ) ;
p r i n t f ( Word2 s t r i n g = %s \n , word2 ) ;
}
str cat2.c

Output
Enter the Word-1:GITAM
Enter the Word-2:UNIVERSITY
Before Concatination:
word-1 string = GITAM
word-2 string = UNIVERSITY
After Concatination:
Word-2 string = UNIVERSITYGITAM
3.1.4

strcmp( )

+ This is a function which compares two strings to find out


whether they are same (or) different.

+ The two strings are compared character by character until there


is a mismatch (or) end of one of the strings is reached, whichever
occurs first.
+ If the two strings are identical, strcmp( ) returns a value zero(0).
+ If theyre not, it returns the numeric difference between the
ASCII values of the first non-matching pairs of characters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/ / program t o i l l u s t r a t e STRCMP ( )
# i n c l u d e <s t d i o . h>
{
char nm [ 2 0 ] , nm2 [ 2 0 ] ;
puts ( Enter a s t r i n g ) ;
s c a n n f ( %s ,nm ) ;
p u t s ( E n t e r a n o t h e r s t r i n g t o know i f b o t h
the s t r i n g s are equal ) ;
s c a n f ( %d , nm2 ) ;
i f ( s t r c m p ( nm , nm2 ) ==0)
{
p r i n t f ( Both t h e s t r i n g s a r e e q u a l ) ;
}
else
{
p r i n t f ( S t r i n g s are not equal ) ;
}
}
str cmp.c

Output
Enter a string-1: - ifhe
Enter another string-2: ifhe
Both the strings are equal
Output(RE RUN)
Enter a string-1: - ifhe
Enter another string-2: IFHE
Strings are not equal

Puppetting On Strings

ARRAY OF STRINGS

+An array of strings is a two dimensional array. Consider an


example that initializes 5 names in an array of strings and print
them:
1 / W r i t e a program t o d e m o n s t r a t e a r r a y o f
s t r i n g s /
2 # i n c l u d e <s t d i o . h>
3 main ( )
4 {
5 int
j;
6 char name [ 5 ] [ 9 ] = { c h i r u , b a l a y a , nag ,
7 venky , b r a m h i } ;
8 f o r ( j = 0 ; j <5; j ++)
9 p r i n t f ( %s \n , name [ j ] ) ;
10 }
strarray.c

Output
chiru
balaya
nag
venki
brahmi

5
5.1

STRING OPERATIONS

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

length

1 / Write a program t o f i n d t h e l e n g t h of a
s t r i n g /
2 # i n c l u d e <s t d i o . h>
3 main ( )
4 {
5 char s t r [ 1 0 0 ] , i =0 , l e n g t h ;
6 p r i n t f ( Enter a String : ) ;
7 gets ( str ) ;
8 w h i l e ( s t r [ i ] ! = \0 )
9 i ++;
10 l e n g t h = i ;
11 p r i n t f ( \n The l e n g t h o f t h e s t r i n g i s
%d\n , l e n g t h ) ;
12 }

36
37

gets ( str1 ) ;
p r i n t f ( E n t e r t h e SECOND s t r i n g : ) ;
gets ( str2 ) ;
len1= s t r l e n ( s t r 1 ) ;
len2= s t r l e n ( s t r 2 ) ;
i f ( l e n 1 == l e n 2 )
{
w h i l e ( i <l e n 1 )
{
i f ( s t r 1 [ i ]== s t r 2 [ i ] )
i ++;
e l s e break ;
}
i f ( i == l e n 1 )
{
same = 1 ;
p r i n t f ( \nTwo s t r u i n g s a r e e q u a l \n ) ;
}
}
i f ( l e n 1 != l e n 2 )
p r i n t f ( \n Two s t r i n g s a r e n o t e q u a l \n ) ;
i f ( same ==0)
{
i f ( s t r 1 [ i ]> s t r 2 [ i ] )
p r i n t f ( \ nString1 i s g r e a t e r than
s t r i n g 2 \n ) ;
e l s e i f ( s t r 1 [ i ]< s t r 2 [ i ] )
p r i n t f ( \ n s t r i n g 2 i s g r e a t e r than
s t r i n g 1 \n ) ;
}
}
compare.c

Output
Enter FIRST string:hi
Enter SECOND string:Hi
Two strings are same
Output(RE RUN)
Enter FIRST string:hi
Enter SECOND string:hello
Two strings are not same(equal)
second string is greater than first string

length.c

Output
Enter a string: GITAM UNIVERSITY
The length of the string is:16

5.2
1
2
3
4
5
6
7
8

compare

/ W r i t e a program t o compare two s t r i n g s /


# i n c l u d e <s t d i o . h>
# i n c l u d e <s t r i n g . h>
main ( )
{
char s t r 1 [ 5 0 ] , s t r 2 [ 5 0 ] ;
i n t i =0 , l e n 1 =0 , l e n 2 =0 , same = 0 ;
p r i n t f ( E n t e r t h e FIRST s t r i n g : ) ;

5.3

concatenation

1 / W r i t e a program t o c o n c a t t e n a t e two
sring /
2 # i n c l u d e <s t d i o . h>
3 main ( )
4 {
5 char s t r 1 [ 1 0 0 ] , s t r 2 [ 1 0 0 ] , s t r 3 [ 1 0 0 ] ;
6 i n t i =0 , j = 0 ;
7 p r i n t f ( Enter the f i r s t s t r i n g : ) ;
8 gets ( str1 ) ;
9 p r i n t f ( Enter the second s t r i n g : ) ;
10 g e t s ( s t r 2 ) ;
11 w h i l e ( s t r 1 [ i ] ! = \0 )

P.Pavan Kumar

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

{
s t r 3 [ j ]= s t r 1 [ i ] ;
i ++;
j ++;
}
i =0;
w h i l e ( s t r 2 [ i ] ! = \0 )
{
s t r 3 [ j ]= s t r 2 [ i ] ;
i ++;
j ++;
}
s t r 3 [ j ] = \0 ;
p r i n t f ( \ nThe c o n c a t i n a t e d s t r i n g i s : ) ;
puts ( str3 ) ;
}
con cat.c

Output
Enter FIRST string:hi
Enter SECOND string:Hi
The concatinated string is:hiHi
Output(RE RUN)
Enter FIRST string:pavan
Enter SECOND string:mahi
The concatinated string is:pavanmahi

Output
Enter string:UNIVERSITY
Reverse string is:YTISREVINU
Output(RE RUN)
Enter string:GITAM
Reverse string is:MATIG

5.5

Upper-case to Lower-case

1
2
3
4
5
6
7
8
9
10
11
12
13
14

/ / uppercase to lower case


# i n c l u d e <s t d i o . h>
# i n c l u d e <s t r i n g . h>
int main (){
c h a r s t r [20];
int i ;
p r i n t f ( E n t e r any s t r i n g > ) ;
s c a n f ( %s , s t r ) ;
p r i n t f ( The s t r i n g i s >%s , s t r ) ;
f o r ( i = 0 ; i <= s t r l e n ( s t r ) ; i ++) {
i f ( s t r [ i ]>=65&& s t r [ i ] <=90)
s t r [ i ]= s t r [ i ] + 3 2 ;
}
p r i n t f ( \ nThe s t r i n g i n l o w e r c a s e
i s >%s , s t r ) ;
15 r e t u r n 0 ;
16 }
upper2lower.c

5.4

reverse

1 / Program : R e v e r s e S t r i n g W i t h o u t U s i n g
Library Function [ Strrev ] /
2 # i n c l u d e <s t d i o . h>
3 # i n c l u d e <s t r i n g . h>
4
5 v o i d main ( )
6 {
7 char s t r [ 1 0 0 ] , temp ;
8 i n t i , j =0;
9
10 p r i n t f ( n E n t e r t h e s t r i n g : ) ;
11 g e t s ( s t r ) ;
12
13 i = 0 ;
14 j = s t r l e n ( s t r ) 1;
15
16 w h i l e ( i <j )
17
{
18
temp= s t r [ i ] ;
19
s t r [ i ]= s t r [ j ] ;
20
s t r [ j ] = temp ;
21
i ++;
22
j ;
23
}
24 p r i n t f ( n R e v e r s e s t r i n g i s :% s , s t r ) ;
25 r e t u r n ( 0 ) ;
reverse.c

Output
Enter a upper-case letter:U
Equivalent lower-case letter :u
Output(RE RUN)
Enter a upper-case letter:G
Equivalent lower-case letter :g

SUMMERY

- A string is a character array from which individual characters


can be accessed using a subscript that start from zero. Any string
is terminated with a null character (0 \n0 ) to signify the end of the
character array.
- All the characters of a string array are stored in successive
memory locations.
- A string can be read from the user by using three ways-using
scanf function, using gets() function, (or) using getchar() function
repeatedly?.
- scanf function terminates as soon as it finds a blank space.
- The gets() takes the starting address of the string which will hold
the input. The string inputted using gets() automatically terminated
with a null character.
- A string can be displayed on the screen using three ways-using
printf function, using puts() function (or) using putchar() function
repeatedly.
- The number of characters in the string constitutes the length of
the string.

Puppetting On Strings

{
char str2[ ] = with C;
strcpy(str1, str2);
printf(\n %s,str1);
}

- Appending one string to another string involves copying the


contents of the source string at the end of the destination string.
There is a library function strcat(s1,s2) that concatenates s2 to s1. It
is defined in string.h(Header file).

3. main()
{
char str1[ ] = programming;
{
char str2[ ] = with C;
strcpy(str1, str2);
printf(\n %s,str1);
}

EXCERCISES

7.1

Find errors

1. main()
{
char str1[ ] = programming;
char str2[ ] = in C;
str1 = str2;
printf( \n str1 = %s,str1);
}

4. main()
{
char str1[ ] = programming;
{
char str2[ ] = with C;
strcpy(str1, str2,3);
printf(\n %s,str1);
}

2. main()
{
char str[ ] = {H,e,l,l,o};
printf(\n str = %s,str);
}
3. main()
{
char str[5] = {HELLO};
printf(\n str = %s,str);
}
4. main()
{
char str[10];
strcpy(str1, HELLO, 3);
printf(\n str = %s,str);
}
5. main()
{
char str[10];
strcpy(str, Hello there);
printf(\n str = %s,str);
}
6. main()
{
char str1[10],str2[10];
printf(\n str1 = %s and str2 = %s,str1,str2);
}

7.2

Find the output

1. main()
{
char str1[ ] = {H,I};
char str2[ ] = {H,I,\0};
if(strcmp(str1 , str2)==0)
printf(\n The strings are equal);
else
printf(\n The strings are not equal);
}

5. main()
{
char str1[ ] = programming;
char str2[ ] = gitam;
printf(%d,strcpy(str1, str2,3));
}

REVIEW QUESTIONS
1. Explain the following string handling functions strlen(),
strcpy(), strcat(), strrev() strcmp() + Standard Library
String Functions
2. Write a program to count the number of characters, number of
blank spaces and number of vowels in a given string
3. Give a note on strspn and strchr functions
4. Write a program to copy contents of one sting to another,
extract substring and store it in another string without using
standard string functions
5. Develop a program in C to arrange the names in alphabetical
order
6. Write a C program to concatenate two input strings using arrays
(with out using string handling functions) + con cat.c
7. Write a C program to check the given String is palindrome or
not using string built in functions + reverse.c
8. Write a C program to check the given String is palindrome or
not with out using string built in functions.
9. Define String and explain the ways of reading string
(Scanf(),gets(),iterative statement)

10. Write a short note on String Input Output functions


11. Write a pointer version of the function strcmp to compare two
strings s and t + strcmp.c

2. main()
{
char str1[ ] = programming;

P.Pavan Kumar

APPENDIX

Table 3. Strings representation in computer memory

Charecter:
ASCII CODE:

M
77

y
121

32

a
97

g
103

e
101

32

i
105

s
115

32

2
50

32

(
40

t
116

w
119

0
111

)
41

\0
0

You might also like