Upload
donhu
View
228
Download
1
Embed Size (px)
Citation preview
Chapter 9 Strings
Original Slides:
Kun-Mao Chao
Updated:
Andrew Bartczak
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-2
Strings
• C implements the string data structure using arrays of type char.
• You have already used the string extensively.
– printf(“This program is terminated!\n”);
– #define ERR_Message “Error!!”
• Since string is an array, the declaration of a string is the same as declaring a char array.
– char string_var[30];
– char string_var[20] = “Initial value”;
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-3
String Literals
• String literal values are represented by sequences of
characters between double quotes (“)
• Examples
– “” - empty string
– “hello”
• “a” versus ‘a’
– ‘a’ is a single character value (stored in 1 byte) as the ASCII
value for a
– “a” is an array with two characters, the first is a, the second is
the character value \0
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-4
Referring to String Literals
• String literal is an array, can refer to a single character
from the literal as a character
• Example:
printf(“%c”,”hello”[1]);
outputs the character ‘e’
• During compilation, C creates space for each string
literal (# of characters in the literal + 1)
– referring to the literal refers to that space (as if it is
an array)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-5
Duplicate String Literals
• Each string literal in a C program is stored at a different
location
• So even if the string literals contain the same string,
they are not equal (in the == sense)
• Example:
– char string1[6] = “hello”;
– char string2[6] = “hello”;
– but string1 does not equal string2 (they are stored at different
locations)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-6
Changing String Variables
• Allocate an array of a size large enough to hold the string (plus 1 extra value for the delimiter)
• Examples (with initialization):
char str1[6] = “Hello”;
char str2[] = “Hello”;
char *str3 = “Hello”;
char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’\0’};
• Note, each variable is considered a constant in that the space it is connected to cannot be changed
str1 = str2; /* not allowable, but we can copy the contents
of str2 to str1 (more later) */
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-7
Changing String Variables cont.
• Can change parts of a string variable
char str1[6] = “hello”;
str1[0] = ‘y’;
/* str1 is now “yello” */
str1[4] = ‘\0’;
/* str1 is now “yell” */
• Important to retain delimiter (replacing str1[5] in the original string with something other than ‘\0’ makes a string that does not end)
• Have to stay within limits of array
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-8
Memory Storage for a String
• The string is always ended with a null character
‘\0’.
• The characters after the null character are
ignored.
• e.g., char str[20] = “Initial value”;
n i t i a l v a l u e ? ? … I \0
[0] [13]
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-9
Distinction Between Characters and Strings
• The representation of a char (e.g., ‘Q’) and a
string (e.g., “Q”) is essentially different.
– A string is an array of characters ended with the null
character.
Q
Character ‘Q’
Q \0
String “Q”
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-10
Arrays of Strings Introduction
• An array of strings is a two-dimensional array of
characters in which each row is one string.
– char names[People][Length];
– char month[5][10] = {“January”,
“February”, “March”, “April”,
“May”};
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-11
String Input
• Use %s field specification in scanf to read string
– ignores leading white space
– reads characters until next white space encountered
– C stores null (\0) char after last non-white space char
– Reads into array (no & before name, array is a pointer)
• Example:
char Name[11];
scanf(“%s”,Name);
• Problem: no limit on number of characters read (need one for delimiter), if too many characters for array, problems may occur
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-12
String Input (cont)
• Can use the width value in the field specification to
limit the number of characters read:
char Name[11];
scanf(“%10s”,Name);
• Remember, you need one space for the \0
– width should be one less than size of array
• Strings shorter than the field specification are read normally, but C always stops after reading 10 characters
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-13
String Input (cont)
• Edit set input %[ListofChars]
– ListofChars specifies set of characters (called scan set)
– Characters read as long as character falls in scan set
– Stops when first non scan set character encountered
– Note, does not ignored leading white space
– Any character may be specified except ]
– Putting ^ at the start to negate the set (any character BUT list is allowed)
• Examples:
scanf(“%[-+0123456789]”,Number);
scanf(“%[^\n]”,Line); /* read until newline char */
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-14
String Output
• Use %s field specification in printf:
characters in string printed until \0 encountered
char Name[10] = “Rich”;
printf(“|%s|”,Name); /* outputs |Rich| */
• Can use width value to print string in space:
printf(“|%10s|”,Name); /* outputs | Rich| */
• Use - flag to left justify:
printf(“|%-10s|”,Name); /* outputs |Rich | */
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-15
Input/Output of a String Example
#include <stdio.h>
void main() {
char LastName[11];
char FirstName[11];
printf("Enter your name (last , first): ");
scanf("%10s%*[^,],%10s",LastName,FirstName);
printf("Nice to meet you %s %s\n",
FirstName,LastName);
}
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-16
Input/Output of a String
• The placeholder %s is used to represent string
arguments in printf and scanf.
– printf(“Topic: %s\n”, string_var);
• The string can be right-justified by placing a
positive number in the placeholder.
– printf(“%8s”, str);
• The string can be left-justified by placing a
negative number in the placeholder.
– Printf(“%-8s”, str);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-17
Right and Left Justification of
Strings
The “%8s” placeholder displays a string which is right-
justified and in 8-columns width.
If the actual string is longer than the width, the displayed field
is expanded with no padding.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-18
An Example of Manipulating String
with scanf and printf
The dept is the initial memory address
of the string argument. Thus we don’t
apply the & operator on it.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-19
Execution of scanf ("%s", dept);
• Whenever encountering a white space, the scanning stops
and scanf places the null character at the end of the string.
• e.g., if the user types “MATH 1234 TR 1800,” the string
“MATH” along with ‘0’ is stored into dept.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-20
Array of Strings
• Sometimes useful to have an array of string values
• Each string could be of different length (producing a
ragged string array)
• Example:
char *MonthNames[13]; /* an array of 13 strings */
MonthNames[1] = “January”; /* String with 8 chars */
MonthNames[2] = “February”; /* String with 9 chars */
MonthNames[3] = “March”; /* String with 6 chars */
etc.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-21
Array of Strings Example
#include <stdio.h>
void main() {
char *days[7];
char TheDay[10];
int day;
days[0] = "Sunday";
days[1] = "Monday";
days[2] = "Tuesday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saturday";
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-22
Array of Strings Example
printf("Please enter a day: ");
scanf("%9s",TheDay);
day = 0;
while ((day < 7) && (!samestring(TheDay,days[day])))
day++;
if (day < 7)
printf("%s is day %d.\n",TheDay,day);
else
printf("No day %s!\n",TheDay);
}
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-23
Array of Strings Example
int samestring(char *s1, char *s2) {
int i;
/* Not same if not of same length */
if (strlen(s1) != strlen(s2))
return 0;
/* look at each character in turn */
for (i = 0; i < strlen(s1); i++)
/* if a character differs, string not same */
if (s1[i] != s2[i]) return 0;
return 1;
}
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-24
String Library Functions
• The string can not be copied by the assignment
operator ‘=’.
– e..g, “str = “Test String”” is not valid.
• C provides string manipulating functions in the
“string.h” library.
– The complete list of these functions can be found in
Appendix B of the textbook.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-25
Some String Functions from String.h
Function Purpose Example
strlen Returns the number of characters
in a string strlen(“Hi”); // ret. 2
strcpy Makes a copy of a string strcpy(s1, “Hi”);
strcat Appends a string to the end of
another string strcat(s1, “more”);
strcmp Compare two strings
alphabetically strcmp(s1, “Hu”);
strcspn Calculate length of initial segment
of str1 characters not in str2. strcspn(“There ”, “er”);
strtok Breaks a string into tokens by
delimiters.
strtok(“Hi, Chao”, “ ,”);
strchr Searches the first occurrence of a
character in a string. strchr(s1,’u’);
strstr Searches the first occurrence of a
substring in a string. strchr(s1, “Hi”);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-26
Functions strcpy and strncpy
• Function strcpy copies the string in the second argument into the first argument.
– e.g., strcpy(dest, “test string”);
– The null character is appended at the end automatically.
– If source string is longer than the destination string, the overflow characters may occupy the memory space used by other variables.
• Function strncpy copies the string by specifying the number of characters to copy.
– You have to place the null character manually.
– e.g., strncpy(dest, “test string”, 6); dest[6] = ‘\0’;
– If source string is longer than the destination string, the overflow characters are discarded automatically.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-27
Extracting Substring of a String (1/2)
• We can use strncpy to extract substring of one string.
– e.g., strncpy(result, s1, 9);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-28
Extracting Substring of a String (2/2)
• e.g., strncpy(result, &s1[5], 2);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-29
Functions strcat,strcat and strlen
• Functions strcat and strncat concatenate the fist string argument with the second string argument. – strcat(dest, “more..”);
– strncat(dest, “more..”, 3);
• Function strlen is often used to check the length of a string (i.e., the number of characters before the fist null character).
– e.g., dest[6] = “Hello”; strncat(dest, “more”, 5-strlen(dest)); dest[5] = ‘\0’;
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-30
Functions strchr and strstr
• Function strchr searches for the first occurrence of a character ch in a string str.
– e.g.,dest[6] = “Hello”
strchr(dest, ‘H’);
• Function strstr searches for the first occurrence of a substring substr in a string str.
– e.g., dest[6] = “Hello”; strstr(dest, “He”);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-31
Function strcspn
• Function strcspn returns the number of characters in the initial segment of string str1 which are not in the string
– e.g.,dest[6] = “Hello”
ivalue = strcspn(dest, “aho”);
The return ivalue is 4 since string dest spans four characters before ‘o’ is found.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-32
String Comparison (1/2)
• Suppose there are two strings, str1 and str2.
– The condition str1 < str2 compare the initial memory
address of str1 and of str2.
• The comparison between two strings is done by
comparing each corresponding character in them.
– The characters are compared against the ASCII table.
– “thrill” < “throw” since ‘i’ < ‘o’;
– “joy” < joyous“;
• The standard string comparison uses the strcmp and
strncmp functions.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-33
String Comparison (2/2)
Relationship Returned Value Example
str1 < str2 Negative “Hello”< “Hi”
str1 = str2 0 “Hi” = “Hi”
str1 > str2 Positive “Hi” > “Hello”
• e.g., we can check if two strings are the same by
if(strcmp(str1, str2) != 0)
printf(“The two strings are different!”);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-34
Input/Output of Characters and
Strings
• The stdio library provides getchar function which gets the next character from the standard input.
– ch = getchar(); is the same as scanf(“%c”, &ch);
– Similar function are putchar, gets, puts:
char str[50] ;
printf(“Enter a staring: “) ;
gets(str);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-35
Input/Output of Characters Example
#include<stdio.h>
int main()
{
char c;
printf(“Enter character: “);
c = getc(stdin);
printf(“Character entered: “);
putc(c, stdout);
return(0);
}
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-36
Input/Output of Strings Example
#include<stdio.h>
int main()
{
char str[50];
printf(“Enter a string: “);
gets(str);
printf(“You entered %s”, str);
return(0);
}
#include <stdio.h> int main() { char str[50]; printf("Enter a string : "); gets(str); printf("You entered: %s", str); return(0); }
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-37
File Input/Output of Characters and
Strings
• For IO from/to the file, the stdio library also provides corresponding functions.
– getc: reads a character from a file.
– Similar functions are putc, fgets, fputs.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-38
Character Analysis and Conversion
• The <ctype.h> library defines facilities for character
analysis and conversion.
Functions Description
isalpha Check if the argument is a letter
isdigit Check if the argument is one of the ten digits
isspace Check if argument is a space, newline or tab.
tolower Converts the lowercase letters in the
argument to upper case letters.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-39
Conversions Between Strings
Numbers
• The <stdlib.h> defines some basic functions for
conversion from strings to numbers:
– atoi(“123”) converts a string to an integer.
– atol(“123”) converts a string to a long integer.
– atof(“12.3”) converts a string to a float.
• However, there is no functions such as itoa, itof,
…etc,
– because there is a function called sprintf which can
converts many formats to a string.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 9-40
The sprintf and sscanf Functions
• The sprintf function substitutes values for
placeholders just as printf does except that it
stores the result into a character array
– sprintf(s, “%d%d%d”, mon, day,
year);
• The sscanf function works exactly like scanf
except that it takes data from the string as its
input argument.
– sscanf(“ 11 22.2 Hello”, “%d%lf%s”,
&num, &val, word);