Strings

Lecture 8 String
1.
2.
3.
4.
5.
Concept of strings
String and pointers
Array of strings
String operations
String library
© Oxford University Press 2014. All rights reserved.
1. Concepts of String
• A string is a null-terminated character array. This means that after
the last character, a null character (‘\0’) is stored to signify the
end of the character array.
• The general form of declaring a string is
char str[size];
• For example if we write,
char str[] = “HELLO”;
© Oxford University Press 2014. All rights reserved.
Concepts of String
• We are declaring a character array with 5 characters namely, H, E,
L, L and O. Besides, a null character (‘\0’) is stored at the end of
the string. So, the internal representation of the string becomes
HELLO‘\0’.
• Note that to store a string of length 5, we need 5 + 1 locations (1
extra for the null character).
• The name of the character array (or the string) is a pointer to the
beginning of the string.
© Oxford University Press 2014. All rights reserved.
Example
char name[ ] = “cp264”;
printf(“%s”, name); // will print cp264
name array has size 6.
or
char name[] = {‘c’, ‘p’, ‘2’, ‘6’, ‘4’, ‘\0’};
© Oxford University Press 2014. All rights reserved.
Example
use more space for string
char name[ 20 ]; //name hold a string of 19 characters.
name[0] = ‘c’; // or name[0] = 99;
name[1] = ‘p’;
name[2] = ‘2’;
name[3] = ‘6’;
name[4] = ‘4’;
name[5] = ‘\0’; // or name[5] = 0;
printf(“%s”, name);
Alternative declaration initialization
char name[20] = “cp264”;
char name[20] = {‘c’, ‘p’, ‘2’, ‘6’, ‘4’, ‘\0’};
© Oxford University Press 2014. All rights reserved.
2. Pointers and Strings
Since string is char array, array pointers and
operations apply to string
char name[20] = “cp264”;
char *p;
p = &name[0];
printf("%c\n", *p);
printf("%c\n", *(p+3));
printf("%s\n", p+2);
// what this print?
// what this print?
// what this print?
© Oxford University Press 2014. All rights reserved.
String pointer
char *p1 = "cp264";
printf("%s\n", p1);
printf("%c\n", *(p1+2));
Note: if a string is declared like
char *a = “cp264”;
Then a can only be read.
*(a+1) = ‘c’; is not allowed
© Oxford University Press 2014. All rights reserved.
Pointers and Strings
Now, consider the following program that prints a text.
#include<stdio.h>
main()
{
char str[] = “Oxford”;
char *pstr = str;
printf(“\n The string is : ”);
while( *pstr != ‘\0’)
{
printf(“%c’, *pstr);
pstr++;
}
© Oxford University Press 2014. All rights reserved.
3. Arrays of Strings
• Suppose there are 20 students in a class and we need a string that
stores names of all the 20 students. How can this be done? Here, we
need a string of strings or an array of strings. Such an array of strings
would store 20 individual strings.
• An array of strings is declared as: char names[20][30];
• Here, the first index will specify how many strings are needed and the
second index specifies the length of every individual string. So we
allocate space for 20 names where each name can be maximum 30
characters long.
© Oxford University Press 2014. All rights reserved.
example
char name[5][40]
= {"Data strucure II", "C programming language", "cp264"};
printf("\n%s", name[2]);
printf("\n%s", name[0]);
printf("\n%s", name[1]);
cp264
Data strucure II
C programming language
name[i] is char pointer to (i-1) th string
printf("\n%c", *(name5[1]+2));
// what this print?
*(name[1]+2) = ‘A’; // this is allowed
© Oxford University Press 2014. All rights reserved.
// array of char pointer, each pointer point to a string
char *name[]
= {"Data strucure II", "C programming language", "cp264"};
printf("\n%s", name[2]);
printf("\n%s", name[0]);
printf("\n%s", name[1]);
// *(name[1]+2) = ‘A’; this is not allowed
© Oxford University Press 2014. All rights reserved.
Command Line Arguments
main( int argc, char *argv[] )
argc = # command line arguments
argv = command line arguments, array of strings
$ a.out argument1 argument2
argc = 3
argv[ 0 ] = “a.out”
argv[ 1 ] = “argument1”
argv[ 2 ] = “argument2”
© Oxford University Press 2014. All rights reserved.
4. String operations
1.
2.
3.
4.
5.
6.
7.
8.
Copy string
Read string
Write string
Length of a string
Change case
Concatenate/appending string
Compare string
…
© Oxford University Press 2014. All rights reserved.
String copy by pointer
char a[] = “C programming
language”;
char c[30];
int i;
// copy string
for (i = 0; *(a+i) !='\0'; i++)
*(c+i) = *(a+i);
*(c+i) = ‘\0’; // add NULL to end
char d[30];
char *p1, *p2;
p1 = a;
p2 = d;
for (; *p1!='\0'; p1++,p2++)
*p2 = *p1;
*p2 = '\0'; // add NULL to end
//print string
for (i = 0; c[i] !='\0'; i++)
printf("%c", c[i]);
printf("%s\n", d);
© Oxford University Press 2014. All rights reserved.
Main(){
char a[] = “C programming language”;
char b[30];
copy_string(a, b);
}
void copy_string(char *from, char *to){
// version 1
for (; *from!='\0'; from++,to++)
*to = *from;
*to = '\0';
}
void copy_string(char *from, char *to){
// version 2
while ((*to = * from) != ‘\0’) { to++; from++; }
}
void copy_string(char *from, char *to){
// version 3
while ((*to++ = *from++) != ‘\0’) ;
}
© Oxford University Press 2014. All rights reserved.
Reading Strings
If we declare a string by writing
char str[100];
Then str can be read from the user by using three ways
using scanf function
using gets() function
using getchar() function repeatedly
str can be read using scanf() by writing
scanf(“%s”, str);
str can be read by writing
gets(str);
gets() takes the starting address of the string which will hold the input.
The string inputted using gets() is automatically terminated with a null
character.
© Oxford University Press 2014. All rights reserved.
Reading Strings
• str can also be read by calling the getchar() function repeatedly
to read a sequence of single characters (unless a terminating
character is entered) and simultaneously storing it in a
character array.
i=0;
ch = getchar ();
while(ch != '*’)
{
str[i] = ch;
i++;
ch = getchar;
}
str[i] = '\0';
© Oxford University Press 2014. All rights reserved.
Get string from Key board input
c
p
2
6
4
1
7
char name[20];
scanf(“%s”, name);
name has value cp264
fgets(name, sizeof(name), stdin);
name has value cp264 17
© Oxford University Press 2014. All rights reserved.
<enter>
Writing Strings
• Strings can be displayed on screen using three ways
using printf() function
using puts() function
using putchar() function repeatedly
• str can be displayed using printf() by writing
printf(“%s”, str);
• str can be displayed by writing
puts(str);
© Oxford University Press 2014. All rights reserved.
Writing Strings
str can also be written by calling the putchar() repeatedly to print a
sequence of single characters
i=0;
while(str[i] != '\0’)
{
putchar(str[i]);
i++;
}
© Oxford University Press 2014. All rights reserved.
Finding Length of a String
• The number of characters in a string constitutes the length of the
string.
• For example, LENGTH(“C PROGRAMMING IS FUN”) will return 20.
Note that even blank spaces are counted as characters in the string.
ALGORITHM TO CALCULATE THE LENGTH OF A STRING
Step 1: [INITIALIZE] SET I = 0
Step 2: Repeat Step 3 while STR[I] != NULL
Step 3:
SET I = I + 1
[END OF LOOP]
Step 4: SET LENGTH = I
Step 5: END
© Oxford University Press 2014. All rights reserved.
Converting Characters of a String into Upper Case
ALGORITHM TO CONVERT THE CHARACTERS OF STRING INTO
UPPER CASE
Step1: [Initialize] SET I=0
Step 2: Repeat Step 3 while STR[I] != NULL
Step 3:
IF STR[1] >= ‘a’ AND STR[I] <= ‘z’
SET Upperstr[I] = STR[I] - 32
ELSE
SET Upperstr[I] = STR[I]
[END OF IF]
[END OF LOOP]
Step 4: SET Upperstr[I] = NULL
Step 5: EXIT
© Oxford University Press 2014. All rights reserved.
4. String library
#include <string.h>
1. String copy function
char *strcpy( char *destination, char *source );
e.g.
char name[20];
strcpy( name, “cp264 data structures” );
2. String length function
int strlen( const char *str ); /* returns string length */
e.g.
printf(“%d”, sizeof(name)); // what value ?
printf(“%d”, strlen(name)); // what value ?
© Oxford University Press 2014. All rights reserved.
3. Memory copy function
void *memcpy(void *str1, const void *str2, size_t
n);
// copies n characters from memory area str2 to
memory area str1.
e..g
const char src[50] = " cp264 data structures ";
char dest[50];
memcpy(dest, src, strlen(src)+1);
© Oxford University Press 2014. All rights reserved.
4. String library
#include <string.h>
char *strcpy( char *destination, char *source );
e.g.
char name[20];
strcpy( name, “cp264 data structures” );
const char src[50] = "memory copy function"; char
dest[50]; printf("Before memcpy dest = %s\n", dest);
memcpy(dest, src, strlen(src)+1);
• Get string lenghth
int strlen( const char *str ); /* returns string length */
e.g.
printf(“%d”, sizeof(name)); // what value ?
printf(“%d”, strlen(name));
// what value ?
© Oxford University Press 2014. All rights reserved.
• Concatenate two strings
char *strcat( char *destination, char *source );
– Source is appended to destination
char s1[20] = “hello “;
char s2[20] = “world.”;
strcat(s1, s2); // s1 has value hello world.
• Compare two strings
int strcmp( const char *first, const char *second ); /* ASCII order */
– value = 0 if two strings are identical
– value = -1 if first is less than second
– value = 1 if first is greater than second
char s1[20] = “hello “;
char s2[20] = “world.”;
printf(“%d”, strcmp(s1, s2)); // what’s the output?
© Oxford University Press 2014. All rights reserved.