STRING
PDPU
What are strings?
A one dimensional array of characters
terminated by a NULL (‘\0’) (ASCII value
0).
Used to manipulate text such as words
and sentences.
Each character in the array occupies one
byte of memory.
Declaring a string…
char name[10];
– can store maximum 9 characters.
char name[10] = “PDPU”;
P D P U \0
Declaring a string…
char name[ ] = “PDPU”;
char name[ ] = { ‘P’ , ‘D’ , ‘P’ , ‘U’ , ‘\0’ };
P D P U \0
Program to print a string character by
character…
void printstring (void)
{
char name[ ] = “PDPU”;
int i = 0 ;
while (name[ i ] != ‘\0’)
{
cout << name[ i++ ];
};
}
Program to print a string (char by char)
using pointer…
void printstring (void)
{
char name[ ] = “PDPU”;
char * ptr = name;
while (*ptr != ‘\0’)
{
cout << *ptr ; ptr++;
}
}
Standard library functions
(Defined in string.h)…
strlen(s) : returns length of a string s.
strcpy(t,s) : copies source string to target
string.
strlwr(s) : converts a string to lower case.
strupr(s) : converts a string to upper case.
strcmp(t,s) : compares whether two
strings are equal or not.
strrev(s) : reverses string s.
int strlen ( char * ) function
returns length of the string.
e.g. char s1[30] = “Computer Programming”;
int l = strlen(s1) will store 20 in l.
cout << strlen(s1) will display 20 on screen.
It will not count last terminal character
(NULL ‘\0’).
Our own function to count length of a
string…
int xstrlen ( char * s)
{
int length = 0;
while ( *s != ‘\0’ )
{
length++; s++;
};
return (length);
}
strcpy ( ) function…
char s1[30];
s1 = “Computer Programming” // illegal.
we have to use strcpy function.
e.g. strcpy(s1,“Computer Programming”);
will copy “Computer Programming” in s1.
Our own function to copy one string
to another string…
void xstrcpy(char * t, const char * s)
{
while ( *s != ‘\0’ )
{
*t = *s; s++ ; t++;
};
*t = ‘\0’;
}
Can you write your own functions…
To convert a string to a lower case.
To convert a string to an upper case.
To reverse the string.
To concatenate two strings.
To find the position of a character in a
given string.
Two dimensional array of characters…
char name[5][10] = { “Swapnil” , “Prerak” ,
“Tushar” , “Swastika”, “Priyanka” };
2411397060 S w a p n i l \0
2411397070 P r e r a k \0
2411397080 T u s h a r \0
2411397090 S w a s t i k a \0
2411397100 P r i y a n k a \0
name[4] name[4][9]
Using 2-D array of characters
cout << name[0] will display “Swapnil”.
cout << name[4] will display “Priyanka”.
cout << name[3][2] will display ‘a’.
&name[0] or name will display 2411397060.
&name[1] or name+1 will display 2411397070.