Representing Strings and String I/O

Post on 30-Dec-2015

25 views 1 download

description

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 . p rintf (“Hello world”); - PowerPoint PPT Presentation

transcript

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”);

3

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

Declaring and initializing string variables

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];

C does not support strings as a data type

string lengthExamples: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’};

[] array notation

5

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

Reading strings from terminal The familiar input function scanf function can be used with %s

format specifier.char city[10];scanf(“%s”, city);

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.

The ampersand (&) is not required before the variable name. Because city is already address

in memory where string is stored.

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.printf(“%10.4s”, name);

orprintf(“%-10.4s”, name);

%10.4 indicates that the first four characters are to be printed in a field width of 10 columns.

%-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

11

Each string has an address

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.

Very important example!

Address of “are”

Character located at the address “space travellers”

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 isstrcmp( 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 Outputstring a is >Excellence<After strcpy(b, a), string b is now >Excellence<=============String b = >Excellence< and is 10 characters longAfter strcat(b, " "), string b = >Excellence < and is 11 characters longAfter strcat(b, a), string b = >Excellence Excellence< and is 21 characters longstrtok( b, " " ) gives Excellence

Sample Program Output (cont’d)=============string a = Excellence string c = Failurestrcmp( a, c ) gives -1strcmp( c, a ) gives 1strcmp( a, "Excellence" gives 0After strcmp( "CMSC", "IFSM" ), result is -1After strcmp( "IFSM", "CMSC" ), result is 1After strcmp( "CMSC", "CMSC" ), result is 0

Sample Program Output (cont’d)=============atoi( "1234”) gives 1234atof( "1234.5678" ) gives 1234.567800

23

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. 0 if the are equal;b. Negative number if s1 sub-string is less than s2; andc. Positive number , otherwise.

24

Other String Functions

Concatenate the left-most n characters of s2 to the end of s1. s1

s2after(s1, s2, 6)

s1 is a string to search within. s2 is the substring that you want to find.

H e l l o W o r l d \0

K o r e a \0

K o r e a W o r l d \0

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 */

26

Example: reverse characters in an input string

27

Passing parameter to the main function