Vous êtes sur la page 1sur 8

Lecture Notes: C, 2013

PROGRAMMING WITH C (EURCS 105) Pages 1–8

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 characters in the word ”Hello”.


Motivation: Syntax of string:
The programming languages have become increasingly important
with the advancement of computer technology. It is essential to write datatype string name[size]={string contents};
efficient programs in order to handle a large amount of data. Effiecient
high-level languages like C in conjunction with powerful computers If we follow the rule of array initialization then we can write the
have helped in solving large and complex problems in reasonable above statement as follows:
time. Example-1:
Targetted People: char greeting[6] = {’G’, ’I’, ’T’, ’A’, ’M’, ’\0’};
This article targetted at the students of science and engineering,
particularly the undergraduate students of circuital(CSE, IT, EEE,
(or)
ECE,EIE), non-circuital(Mechanical, Civil, Aeronautical) branches char greeting[ ] = {’G’, ’I’, ’T’, ’A’, ’M’, ’\0’};
and those who are interested in learning programming with c.
Learning Objective: (or)
In this article, we will read about array of characters commonly known char greeting[ ] = {”GITAM ”};
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.
Table 1. memory presentation of above-defined string in C
Contact:
)
pavankuamrp@gitam.edu G I T A M ’\0’

2.1 What are Strings


1 INTRODUCTION • The way a group of integers can be stored in an integer array
• In the prior chapter we learnt how to define arrays of differing • Similarly a group of characters can be stored in a character array.
sizes and dimensions, how to initialize arrays, etc. • Character arrays are many a time also called strings.
• With this knowledge under your belt, you should be ready to
handle strings, which are, simply put, a special kind of array. And Character arrays (or) strings are used by programming
strings, the ways to manipulate them are going to be the topics of languages to manipulate text such as words and sentences.
discussion in this article.
• A string constant is a one-dimensional array of characters
terminated by a null ( ‘\0 ’).

2 STRINGS
+ The string in C programming language is actually a one- Actually, you do not place the null character at the end of a string
dimensional array of characters which is terminated by a null constant. The C compiler automatically places the ’\0’ at the end
character ’\0’. of the string when it initializes the array. Let us try to print above
+ Thus a null-terminated string contains the characters that mentioned string:
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. 1


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 ∗ / NOTE-I: ‘\0 ’and ‘0 ’are not same. ASCII value of ‘\0 ’is 0,
2 # i n c l u d e < s t d i o . h> whereas ASCII value of ‘0 ’is 48.
3 i n t main ( ) NOTE-II: The elements of the character array are stored in
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 }
string1.c

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


something as follows:

OUTPUT: Fig. 1. a character array is stored in memory

- Greeting message: GITAM


contiguous memory locations.
Example: The terminating null (‘\0 ’) is important, because it is the only
”My age is 2 (two)”; way the functions that work with a string can know where the
Above statement is a string. The string stored in memory as ASCII string ends. In fact, a string not terminated by a ‘\0 ’is not
codes of the characters that make up the string, appended with really a string, but merely a collection of characters.
0(ASCII value of null). Normally, each character is stored in one • C concedes the fact that you would use strings very often and
byte, and successive characters of the string are stored in successive hence provides a shortcut for initializing strings. For example, the
bytes. string used above can also be initialized as,
- NOTE: char name [8] = ”HAESLER ”;
Memory presentation of above example string is given in
APPENDIX 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
s t r i n g ∗/
2 # i n c l u d e <s t d i o . h>
3 main ( )
3 INITIALIZING STRING
4 {
Following the discussion on character arrays,(i.e., a string), the 5 char name [ ] = ” ICFAI F u n d a t i o n f o r H i g h e r
initialization of a string must have the following form,(this is similar Education ” ;
to initializing a one dimensional array): 6 int i = 0 ;
EXAMPLE: 7 w h i l e ( i <= 38 )
8 {
char month1[]={’J’,’A’,’N’,’U’,’A’,’R’,’Y’,0}; 9 p r i n t f ( ”%c ” , name [ i ] ) ;
- Then the the month is initialized to January. This is perfectly 10 i ++ ;
valid, but C offer a special way to initialize strings. the above string 11 }
can be initialized as: 12 p r i n t f ( ” \n ” ) ;
13 }
(OR) example11.c

Output
char month1[]=”JANUARY”;
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 ] ) ;

2
Puppetting On Strings

10 } 1 / / program t o i l l u s t r a t e STRLEN ( )
11 p r i n t f ( ” \n ” ) ; 2 # i n c l u d e <s t d i o . h>
12 } 3 main ( )
13 ˜ 4 {
example12.c 5 char a r r [ ] = ”FACULTY OF SCIENCE AND
TECHNOLOGY” ;
Output 6 int len1 ;
Faculty of Science and Technology 7 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 ’
• The %s used in printf( ) is a format specification for printing out
8 p r i n t f ( ” \ n s t r i n g = %s l e n g t h = %d ” , a r r ,
a string.
len1 ) ;
• The same specification can be used to receive a string from the 9 }
keyboard, str len.c

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 Output
string ( r e c e i v e a s t r i n g from t h e string = FACULTY OF SCIENCE AND TECHNOLOGY
keyboard ) ∗/ length = 33
2 # i n c l u d e <s t d i o . h>
3 main ( ) 3.1.2 strcpy( )
4 {
5 char name [ 2 5 ] ;
6 p r i n t f ( ” E n t e r y o u r name ” ) ; + This function copies the contents of one string into another.
7 s c a n f ( ”%s ” , name ) ; + The base addresses of the source and target strings should be
8 p r i n t f ( ” H e l l o %s ! \ n ” , name ) ; supplied to this function.
9 }
example13.c 1 / / program t o i l l u s t r a t e STRCPY ( )
2 # i n c l u d e <s t d i o . h>
Output 3 main ( )
Enter your name: MAHI 4 {
Hello MAHI! 5 char s o u r c e [ 5 0 ] = ”FACULTY OF SCIENCE AND
TECHNOLOGY” ;
RE RUN 6 char t a r g e t [ 5 0 ] ;
Enter your name: mahendra kumar paruchuri 7 strcpy ( target , source ) ;
Hello mahendra! 8 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 ) ;
9 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 )
RE RUN ;
10 }
Enter your name: mahendrakumarpruchuri str cpy.c
Hello mahendrakumarpruchuri!
Output
source string = FACULTY OF SCIENCE AND
3.1 Standard Library String Functions
TECHNOLOGY
target string = FACULTY OF SCIENCE AND
Table 2. Standard Library String Functions TECHNOLOGY

Sr.No. Function Use 3.1.3 strcat( )


1. strlen Finds length of a string
2. strcpy Copies a string into another
+This function concatenates the source string at the end of the
3. strcat Appends one string at the end of
target string.
another
Example
4. strcmp Compares two strings
“Bombay ”and “Nagpur ”on concatenation would result into a
string “BombayNagpur ”.

3.1.1 strlen( ) 1 / / program t o i l l u s t r a t e STRCAT ( )


2 # i n c l u d e <s t d i o . h>
+ This function counts the number of characters present in a string. 3 main ( )
4 {

3
P.Pavan Kumar

5 char word1 [ 3 0 ] ; + The two strings are compared character by character until there
6 char word2 [ 3 0 ] ; is a mismatch (or) end of one of the strings is reached, whichever
7 p r i n t f ( ” E n t e r t h e Word−1: ” ) ; occurs first.
8 s c a n f ( ”%s ” , word1 ) ; + If the two strings are identical, strcmp( ) returns a value zero(0).
9 p r i n t f ( ” E n t e r t h e Word−2: ” ) ; + If theyre not, it returns the numeric difference between the
10 s c a n f ( ”%s ” , word2 ) ; ASCII values of the first non-matching pairs of characters.
11 p r i n t f ( ” Before Concatination :\ n” ) ;
12 p r i n t f ( ” \ nword−1 s t r i n g = %s ” , word1 ) ; 1 / / program t o i l l u s t r a t e STRCMP ( )
13 p r i n t f ( ” \ nword−2 s t r i n g = %s \n ” , word2 ) ; 2 # i n c l u d e <s t d i o . h>
14 s t r c a t ( word1 , word2 ) ; 3 {
15 p r i n t f ( ” After Concatination :\ n” ) ; 4 char nm [ 2 0 ] , nm2 [ 2 0 ] ;
16 p r i n t f ( ”Word−1 s t r i n g = %s \n ” , word1 ) ; 5 puts ( ” Enter a s t r i n g − ” ) ;
17 } 6 s c a n n f ( ”%s ” ,nm ) ;
str cat.c 7 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 ” ) ;
Output 8 s c a n f ( ”%d ” , nm2 ) ;
Enter the Word-1:andhra 9 i f ( s t r c m p ( nm , nm2 ) ==0)
Enter the Word-2:pradesh 10 {
Before Concatination: 11 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 ” ) ;
word-1 string = andhra 12 }
word-2 string = pradesh 13 else
After Concatination: 14 {
Word-1 string = andhrapradesh 15 p r i n t f ( ” S t r i n g s are not equal ” ) ;
16 }
1 / / program t o i l l u s t r a t e STRCAT ( ) 17 }
2 # i n c l u d e <s t d i o . h> str cmp.c
3 main ( )
Output
4 {
5 char word1 [ 3 0 ] ; Enter a string-1: - ifhe
6 char word2 [ 3 0 ] ; Enter another string-2: ifhe
7 p r i n t f ( ” E n t e r t h e Word−1: ” ) ; Both the strings are equal
8 s c a n f ( ”%s ” , word1 ) ;
9 p r i n t f ( ” E n t e r t h e Word−2: ” ) ; Output(RE RUN)
10 s c a n f ( ”%s ” , word2 ) ; Enter a string-1: - ifhe
11 p r i n t f ( ” Before Concatination :\ n” ) ; Enter another string-2: IFHE
12 p r i n t f ( ” \ nword−1 s t r i n g = %s ” , word1 ) ; Strings are not equal
13 p r i n t f ( ” \ nword−2 s t r i n g = %s \n ” , word2 ) ;
14 s t r c a t ( word2 , word1 ) ;
15 p r i n t f ( ” After Concatination :\ n” ) ;
16 p r i n t f ( ”Word−2 s t r i n g = %s \n ” , word2 ) ;
17 }
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.

4
Puppetting On Strings

4 ARRAY OF STRINGS 9 gets ( str1 ) ;


+An array of strings is a two dimensional array. Consider an 10 p r i n t f ( ” E n t e r t h e SECOND s t r i n g : ” ) ;
example that initializes 5 names in an array of strings and print 11 gets ( str2 ) ;
them: 12 len1= s t r l e n ( s t r 1 ) ;
13 len2= s t r l e n ( s t r 2 ) ;
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 14 i f ( l e n 1 == l e n 2 )
s t r i n g s ∗/ 15 {
2 # i n c l u d e <s t d i o . h> 16 w h i l e ( i <l e n 1 )
3 main ( ) 17 {
4 { 18 i f ( s t r 1 [ i ]== s t r 2 [ i ] )
5 int j; 19 i ++;
6 char name [ 5 ] [ 9 ] = { ” c h i r u ” , ” b a l a y a ” , ” nag ” , 20 e l s e break ;
7 ” venky ” , ” b r a m h i ” } ; 21 }
8 f o r ( j = 0 ; j <5; j ++) 22 i f ( i == l e n 1 )
9 p r i n t f ( ”%s \n ” , name [ j ] ) ; 23 {
10 } 24 same = 1 ;
25 p r i n t f ( ” \nTwo s t r u i n g s a r e e q u a l \n ” ) ;
strarray.c
26 }
Output 27 }
chiru 28 i f ( l e n 1 != l e n 2 )
balaya 29 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 ” ) ;
nag 30 i f ( same ==0)
venki 31 {
brahmi 32 i f ( s t r 1 [ i ]> s t r 2 [ i ] )
33 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 ” ) ;
34 e l s e i f ( s t r 1 [ i ]< s t r 2 [ i ] )
5 STRING OPERATIONS 35 p r i n t f ( ”\ n s t r i n g 2 i s g r e a t e r than
5.1 length s t r i n g 1 \n ” ) ;
36 }
1 / Write a program t o f i n d t h e l e n g t h of a 37 }
s t r i n g ∗/
compare.c
2 # i n c l u d e <s t d i o . h>
3 main ( ) Output
4 { Enter FIRST string:hi
5 char s t r [ 1 0 0 ] , i =0 , l e n g t h ; Enter SECOND string:Hi
6 p r i n t f ( ” Enter a String : ” ) ; Two strings are same
7 gets ( str ) ;
8 w h i l e ( s t r [ i ] ! = ’ \0 ’ ) Output(RE RUN)
9 i ++;
Enter FIRST string:hi
10 l e n g t h = i ;
Enter SECOND string:hello
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
Two strings are not same(equal)
%d\n ” , l e n g t h ) ;
second string is greater than first string
12 }
length.c

Output 5.3 concatenation


Enter a string: GITAM UNIVERSITY 1 / ∗ W r i t e a program t o c o n c a t t e n a t e two
The length of the string is:16 sring ∗/
5.2 compare 2 # i n c l u d e <s t d i o . h>
3 main ( )
1 / ∗ W r i t e a program t o compare two s t r i n g s ∗ / 4 {
2 # i n c l u d e <s t d i o . h> 5 char s t r 1 [ 1 0 0 ] , s t r 2 [ 1 0 0 ] , s t r 3 [ 1 0 0 ] ;
3 # i n c l u d e <s t r i n g . h> 6 i n t i =0 , j = 0 ;
4 main ( ) 7 p r i n t f ( ” Enter the f i r s t s t r i n g : ” ) ;
5 { 8 gets ( str1 ) ;
6 char s t r 1 [ 5 0 ] , s t r 2 [ 5 0 ] ; 9 p r i n t f ( ” Enter the second s t r i n g : ” ) ;
7 i n t i =0 , l e n 1 =0 , l e n 2 =0 , same = 0 ; 10 g e t s ( s t r 2 ) ;
8 p r i n t f ( ” E n t e r t h e FIRST s t r i n g : ” ) ; 11 w h i l e ( s t r 1 [ i ] ! = ’ \0 ’ )

5
P.Pavan Kumar

12 { Output
13 s t r 3 [ j ]= s t r 1 [ i ] ; Enter string:UNIVERSITY
14 i ++; Reverse string is:YTISREVINU
15 j ++;
16 } Output(RE RUN)
17 i =0; Enter string:GITAM
18 w h i l e ( s t r 2 [ i ] ! = ’ \0 ’ ) Reverse string is:MATIG
19 {
20 s t r 3 [ j ]= s t r 2 [ i ] ;
21 i ++; 5.5 Upper-case to Lower-case
22 j ++;
23 } 1 / / uppercase to lower case
24 s t r 3 [ j ] = ’ \0 ’ ; 2 # i n c l u d e <s t d i o . h>
25 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 : ” ) ; 3 # i n c l u d e <s t r i n g . h>
26 puts ( str3 ) ; 4 int main (){
27 } 5 c h a r s t r [20];
con cat.c
6 int i ;
7 p r i n t f ( ” E n t e r any s t r i n g −>” ) ;
Output 8 s c a n f ( ”%s ” , s t r ) ;
Enter FIRST string:hi 9 p r i n t f ( ” The s t r i n g i s −>%s ” , s t r ) ;
Enter SECOND string:Hi 10 f o r ( i = 0 ; i <= s t r l e n ( s t r ) ; i ++) {
The concatinated string is:hiHi 11 i f ( s t r [ i ]>=65&& s t r [ i ] <=90)
12 s t r [ i ]= s t r [ i ] + 3 2 ;
Output(RE RUN) 13 }
14 p r i n t f ( ” \ nThe s t r i n g i n l o w e r c a s e
Enter FIRST string:pavan
i s −>%s ” , s t r ) ;
Enter SECOND string:mahi
15 r e t u r n 0 ;
The concatinated string is:pavanmahi
16 }
upper2lower.c
5.4 reverse
Output
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 Enter a upper-case letter:U
Library Function [ Strrev ] ∗/ Equivalent lower-case letter :u
2 # i n c l u d e <s t d i o . h> Output(RE RUN)
3 # i n c l u d e <s t r i n g . h>
4 Enter a upper-case letter:G
5 v o i d main ( ) Equivalent lower-case letter :g
6 {
7 char s t r [ 1 0 0 ] , temp ;
8 i n t i , j =0;
9 6 SUMMERY
10 p r i n t f ( ” n E n t e r t h e s t r i n g : ” ) ; - A string is a character array from which individual characters
11 g e t s ( s t r ) ; can be accessed using a subscript that start from zero. Any string
12 is terminated with a null character (0 \n0 ) to signify the end of the
13 i = 0 ; character array.
14 j = s t r l e n ( s t r ) −1; - All the characters of a string array are stored in successive
15 memory locations.
16 w h i l e ( i <j ) - A string can be read from the user by using three ways-using
17 { scanf function, using gets() function, (or) using getchar() function
18 temp= s t r [ i ] ; repeatedly?.
19 s t r [ i ]= s t r [ j ] ; - scanf function terminates as soon as it finds a blank space.
20 s t r [ j ] = temp ; - The gets() takes the starting address of the string which will hold
21 i ++; the input. The string inputted using gets() automatically terminated
22 j −−; with a null character.
23 } - A string can be displayed on the screen using three ways-using
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 ) ; printf function, using puts() function (or) using putchar() function
25 r e t u r n ( 0 ) ; repeatedly.
reverse.c - The number of characters in the string constitutes the length of
the string.

6
Puppetting On Strings

- Appending one string to another string involves copying the {


contents of the source string at the end of the destination string. char str2[ ] = ”with C”;
There is a library function strcat(s1,s2) that concatenates s2 to s1. It strcpy(str1, str2);
is defined in string.h(Header file). printf(”\n %s”,str1);
}
3. main()
7 EXCERCISES {
char str1[ ] = ”programming”;
7.1 Find errors
{
1. main() char str2[ ] = ”with C”;
{ strcpy(str1, str2);
char str1[ ] = ”programming”; printf(”\n %s”,str1);
char str2[ ] = ”in C”; }
str1 = str2;
4. main()
printf(” \n str1 = %s”,str1);
{
}
char str1[ ] = ”programming”;
2. main() {
{ char str2[ ] = ”with C”;
char str[ ] = {’H’,’e’,’l’,’l’,’o’}; strcpy(str1, str2,3);
printf(”\n str = %s”,str); printf(”\n %s”,str1);
} }
3. main() 5. main()
{ {
char str[5] = {”HELLO”}; char str1[ ] = ”programming”;
printf(”\n str = %s”,str); char str2[ ] = ”gitam”;
} printf(”%d”,strcpy(str1, str2,3));
4. main() }
{
char str[10];
strcpy(str1, ”HELLO”, 3); 8 REVIEW QUESTIONS
printf(”\n str = %s”,str); 1. Explain the following string handling functions strlen(),
} strcpy(), strcat(), strrev() strcmp() + Standard Library
5. main() String Functions
{ 2. Write a program to count the number of characters, number of
char str[10]; blank spaces and number of vowels in a given string
strcpy(str, ”Hello there”);
printf(”\n str = %s”,str); 3. Give a note on strspn and strchr functions
} 4. Write a program to copy contents of one sting to another,
6. main() extract substring and store it in another string without using
{ standard string functions
char str1[10],str2[10]; 5. Develop a program in C to arrange the names in alphabetical
printf(”\n str1 = %s and str2 = %s”,str1,str2); order
} 6. Write a C program to concatenate two input strings using arrays
(with out using string handling functions) + con cat.c
7.2 Find the output 7. Write a C program to check the given String is palindrome or
1. main() not using string built in functions + reverse.c
{ 8. Write a C program to check the given String is palindrome or
char str1[ ] = {’H’,’I’}; not with out using string built in functions.
char str2[ ] = {’H’,’I’,’\0’};
if(strcmp(str1 , str2)==0) 9. Define String and explain the ways of reading string
printf(”\n The strings are equal”); (Scanf(),gets(),iterative statement)
else 10. Write a short note on String Input Output functions
printf(”\n The strings are not equal”); 11. Write a pointer version of the function strcmp to compare two
} strings s and t + strcmp.c
2. main()
{
char str1[ ] = ”programming”;

7
P.Pavan Kumar

9 APPENDIX

Table 3. Strings representation in computer memory

Charecter: M y a g e i s 2 ( t w 0 ) \0
ASCII CODE: 77 121 32 97 103 101 32 105 115 32 50 32 40 116 119 111 41 0

Vous aimerez peut-être aussi