Lecture-10-Representing

advertisement
Representing Strings and String I/O
Introduction
 A string is a sequence of characters and is treated as a single data
item.
 A string constant, also termed a string literal, is anything
enclosed in double quotation marks.
printf (“Hello world”);
 To use a double quotation mark within a string, precede the
quotation mark with a backslash (\)
printf (“\”Run, Spot, run!\” exclaimed Dick.\n”);
Introduction
 C standard library provides many functions specifically designed
to work with strings.

Reading and writing strings.
 Combining strings together.

Copying one string to another.
 Comparing strings for equality.

Extracting a portion of a string
3
Declaring and initializing string variables
C does not support strings as a data type
The only support for strings in the C is that the compiler will translate a
quoted string constant into a null-terminated string, which is stored in
static memory.
The general form of declaration of a string variable is
char string_name[size];
Examples:
string length
[] array notation
char city[10];
char name[30];
A string is a char array terminated with a null character (\0).
char city[9] = ”Seoul”;
char city[9] = {‘S’, ‘e’, ‘o’, ‘u’, ‘l’, ‘\0’};
Declaring and initializing string variables
 C permits us to initialize a character array without specifying the
number of elements.
char string [] = {‘G’, ‘O’, ‘O’, ‘D’, ‘\0’};
 The string can be declared with much larger size then the string
size In the initializer.
char str[10] = “GOOD”.
G
O
O
D
\0
\0
\0
\0
\0
\0
Set to zeros
5
Reading strings from terminal
 The familiar input function scanf function can be used with %s
format specifier.
The ampersand (&) is not required before the
char city[10];
scanf(“%s”, city);
variable name. Because city is already address
in memory where string is stored.
 scanf() terminates its input on the first white space it finds.
 white space include:
 blanks,
 tabs
 new lines.
 If the following line of text is typed in at the terminal,
NEW YORK
Then only “NEW” will be read into the array address.
N
E
W
\0
\0
\0
\0
\0
\0
\0
Writing strings to screen


The format %s in the printf function can be used to display an array of
characters that is terminated by the null character.
printf(“%s”, name);
We can specify the precision with which the array is displayed.
%10.4 indicates that the first four characters are
printf(“%10.4s”, name);
to be printed in a field width of 10 columns.
or
printf(“%-10.4s”, name);
%-10.4, the string will be printed left-justified
Example


The printf support feature that allows for variable field width.
printf(“%*.*s\n”, w, d, string)
printf the first d characters of the string in the field width of w.
Alternative to printf()
 We can use putchar() to output the values of a string.
char ch = ‘A’;
putchar (ch).
 We can use this function repeatedly to print out a string.
char name [6] = “PARIS”;
for (I = 0; I < 5; i++)
putchar(name[i]);
putchar(‘\n’)
 Another convenient way of printing string values is to use
the function puts.
puts (str);
Example
Each string has an address
Very important example!
Character located at the
address “space travellers”
Address of “are”
 The %s format should print the string We.
 The %p format produces an address. So if the phrase "are" is an
address, then %p should print the address of the first character in the
string.
11
Missing Operators




There is no string assignment operators.
There are not string comparison operators.
There are not string combination operators.
However, there are built-in functions to do this common tasks.
String functions prototypes defined in
<string.h>
Built-in String Functions
 String assignment. There is no ‘=‘ for string but there is
strcpy( destination, source )
char name[ 25 ];
/* contains nothing */
strcpy( name, “Hilton” ); /* name now contains “Hilton” */
 String comparison. There is no != for string but there is
strcmp( strA, strB );



If strA comes after strB, the function returns a positive number.
Is strB comes last, the function returns a negative number.
If strA and strB are the same thing, the function returns a zero.
result = strcmp( “CMSC”, “IFSM” ); /* negative */
result = strcmp( “IFSM”, “CMSC” ); /* positive */
result = strcmp( “CMSC”, “CMSC” ); /* zero */
Built-in String Functions (cont’d)
 String combination:
strcat( destination, source )
 The source is not changed.
 The destination contain exactly what it had before plus what
was in the source. Nothing else is added. NOTE: If you are
combining a first name and last name for a full name, you
must use another strcat to add the space between them:
strcpy( fullName, firstName);
strcat( fullName, “ “ );
strcat( fullName, lastName );
Built-in String Functions (cont’d)
 Extracting words (tokens) from a string:
/* get the first token (delimited by a blank) */
printf( "%s\n", strtok( str, " " ) );
/* This is more useful after you learn to use pointers. */
Built-in String Functions (cont’d)
 What if I want to get a menu choice, that is the numbers 1 to 4 or the
char ‘q’? Use getchar( ) to get the menu choice, check for ‘q’ and if it
is not, then convert it to a number.
/* convert a string (ASCII) to an integer */
printf( "%d\n", atoi( "1234" ) );
/* convert a string (ASCII) to a float */
printf( "%f\n", atof( "1234.5678" ) );
 How long is the data in the string (not counting the null
terminator)?
stringSize = strlen( strA );
String Libraries
#include files:
#include <stdlib.h>
/* needed by atoi( ) and atof( ) */
#include <string.h>
/* needed by str...( ) functions */
Sample Program
Sample Program
Sample Program Output
string a is >Excellence<
After strcpy(b, a), string b is now >Excellence<
=============
String b = >Excellence< and is 10 characters long
After strcat(b, " "), string b = >Excellence < and is 11 characters long
After strcat(b, a), string b = >Excellence Excellence< and is 21 characters long
strtok( b, " " ) gives Excellence
Sample Program Output (cont’d)
=============
string a = Excellence string c = Failure
strcmp( a, c ) gives -1
strcmp( c, a ) gives 1
strcmp( a, "Excellence" gives 0
After strcmp( "CMSC", "IFSM" ), result is -1
After strcmp( "IFSM", "CMSC" ), result is 1
After strcmp( "CMSC", "CMSC" ), result is 0
Sample Program Output (cont’d)
=============
atoi( "1234”) gives 1234
atof( "1234.5678" ) gives 1234.567800
Other String Functions
The statement copies first n characters of the source string s2 into
the target string s1.
 Since the first n characters may not include the terminating null
character, we have to place it explicitly in the 6th position of s2
s1[n+1] = ‘\0’;
This compares the left-most n characters of s1 to s2 and returns.
a.
b.
c.
0 if the are equal;
Negative number if s1 sub-string is less than s2; and
Positive number , otherwise.
23
Other String Functions
 Concatenate the left-most n characters of s2 to the end of s1.
s1
K
o
r
e
a
\0
H
s2
after(s1, s2, 6)
K
e
l
l
o
W
o
r
l
d
\0
o
r
e
a
W
o
r
l
d
\0
 s1 is a string to search within.
 s2 is the substring that you want to find.
24
Array Versus Pointer*
You can use pointer notation to set up a string.
const char *m3 = "\nEnough about me -- what's your name?";
This declaration is very nearly the same as this one:
char m3[] = "\nEnough about me -- what's your name?"
In short, initializing the array copies a string from static storage to the array, whereas
initializing the pointer merely copies the address of the string.
char heart[] = "I love Tillie!";
char *head = "I love Millie!";
The difference is that the array name heart is a constant, but the pointer head is a variable.
head = heart; /* head now points
to the array heart */
heart = head; /* illegal construction
*/
Example: reverse characters in an input string
26
Passing parameter to the main function
27
Download