dale roberts department of computer and information science, school of science, iupui c-style...
TRANSCRIPT
Dale Roberts
Department of Computer and Information Science,Department of Computer and Information Science,School of Science, IUPUISchool of Science, IUPUI
C-Style StringsStrings and String Functions
Dale Roberts, LecturerDale Roberts, Lecturer
IUPUIIUPUI
[email protected]@cs.iupui.edu
Dale Roberts
Character arraysCharacter arraysString is really a static array of characters, ex: String is really a static array of characters, ex: “first”“first” Character arrays can be initialized using string literalsCharacter arrays can be initialized using string literals
char string1[] = "first";char string1[] = "first";Null character Null character '\0''\0' terminates terminates strings strings
string1string1 actually has 6 elements actually has 6 elementsIt is equivalent to It is equivalent to charchar string1[]string1[] == {{ 'f','f', 'i','i', 'r','r', 's','s', 't','t', '\'\0'0' };};
Can access individual charactersCan access individual charactersstring1[string1[ 33 ] is character ‘s’] is character ‘s’
Array name is address of array, so & not needed for scanf Array name is address of array, so & not needed for scanf char char char string2[20];char string2[20];
scanf(scanf( "%s","%s", string2string2 ); ); Can read a string with max of size 19 and a null character.Can read a string with max of size 19 and a null character.Reads characters until whitespace (Reads characters until whitespace (space, tab, carriage-return, newline, space, tab, carriage-return, newline, vertical tab) vertical tab) encounteredencounteredCan write beyond end of array, be carefulCan write beyond end of array, be careful
Character ArraysCharacter Arrays
f i r s t \0
Null character (indicates string termination)
& is NOT used, why?
Dale Roberts
Fundamentals of Strings and CharactersFundamentals of Strings and Characters
CharactersCharactersBuilding blocks of programsBuilding blocks of programs
Every program is a sequence of meaningfully grouped charactersEvery program is a sequence of meaningfully grouped characters
Character constantCharacter constantAn An intint value represented as a character in single quotes value represented as a character in single quotes'z''z' represents the integer value of represents the integer value of zz
StringsStringsSeries of characters treated as a single unitSeries of characters treated as a single unit
Can include letters, digits and special characters (Can include letters, digits and special characters (**, , //, , $$))
String literal (string constant) - written in double quotesString literal (string constant) - written in double quotes"Hello""Hello"
Strings are arrays of charactersStrings are arrays of charactersString a pointer to first characterString a pointer to first characterValue of string is the address of first characterValue of string is the address of first character
Dale Roberts
Fundamentals of Strings and CharactersFundamentals of Strings and Characters
String declarationsString declarationsDeclare as a character array or a variable of type Declare as a character array or a variable of type char *char *
char color[] = "blue";char color[] = "blue";
char *colorPtr = "blue";char *colorPtr = "blue";
Remember that strings represented as character arrays Remember that strings represented as character arrays end with end with '\0''\0'
colorcolor has has 55 elements elements
Inputting stringsInputting stringsUse Use scanfscanf
scanf("%s", word);scanf("%s", word);
Copies input into Copies input into word[]word[]
Do not need Do not need && (because a string is a pointer) (because a string is a pointer)
Remember to leave room in the array for Remember to leave room in the array for '\0''\0'
Dale Roberts
Command-Line ArgumentsCommand-Line ArgumentsExampleExample: print out the arguments. ex: : print out the arguments. ex: hello worldhello worldmain (int argc, char *argv[])main (int argc, char *argv[]){{ int i;int i; for (i = 1; i < argc; i++)for (i = 1; i < argc; i++) printf(“%s%c”, argv[i], (i < argc-1) ? ‘ ’ : ‘\n’);printf(“%s%c”, argv[i], (i < argc-1) ? ‘ ’ : ‘\n’);}}
main (int argc, char *argv[])main (int argc, char *argv[]){{ while (--argc > 0)while (--argc > 0) printf(“%s%c”, *++argv, (argc > 1) ? ‘ ’ : ‘\n’);printf(“%s%c”, *++argv, (argc > 1) ? ‘ ’ : ‘\n’);}}
main (int argc, char *argv[])main (int argc, char *argv[]){{ while (--argc > 0)while (--argc > 0) printf((argc > 1) ? “%s “ ; “%s\n“, *++argv);printf((argc > 1) ? “%s “ ; “%s\n“, *++argv);}}
Dale Roberts
String Manipulation FunctionsString Manipulation Functions
String handling library has functions toString handling library has functions toManipulate string dataManipulate string data
Search stringsSearch strings
Tokenize stringsTokenize strings
Determine string lengthDetermine string length
Function prototype Function description char *strcpy( char *s1, const char *s2 )
Copies string s2 into array s1. The value of s1 is returned.
char *strncpy( char *s1, const char *s2, size_t n )
Copies at most n characters of string s2 into array s1. The value of s1 is returned.
char *strcat( char *s1, const char *s2 )
Appends string s2 to array s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned.
char *strncat( char *s1, const char *s2, size_t n )
Appends at most n characters of string s2 to array s1. The first character of s2 overwrites the terminating null character of s1. The value of s1 is returned.
Dale Roberts
1. Initialize 1. Initialize variablesvariables
2. Function calls2. Function calls
3. Print3. Print
Program OutputProgram Output
1 /* Fig. 8.19: fig08_19.c
2 Using strcat and strncat */
3 #include <stdio.h>
4 #include <string.h>
5
6 int main()
7 {
8 char s1[ 20 ] = "Happy ";
9 char s2[] = "New Year ";
10 char s3[ 40 ] = "";
11
12 printf( "s1 = %s\ns2 = %s\n", s1, s2 );
13 printf( "strcat( s1, s2 ) = %s\n", strcat( s1, s2 ) );
14 printf( "strncat( s3, s1, 6 ) = %s\n", strncat( s3, s1, 6 ) );
15 printf( "strcat( s3, s1 ) = %s\n", strcat( s3, s1 ) );
16 return 0;
17 }
s1 = Happy
s2 = New Year
strcat( s1, s2 ) = Happy New Year
strncat( s3, s1, 6 ) = Happy
strcat( s3, s1 ) = Happy Happy New Year
Dale Roberts
Other Functions of the String Handling LibraryOther Functions of the String Handling Library
char *strerror( int errornum );char *strerror( int errornum ); Creates a system-dependent error message based on Creates a system-dependent error message based on errornumerrornum
Returns a pointer to the stringReturns a pointer to the string
size_t strlen( const char *s ); size_t strlen( const char *s ); Returns the number of characters (before Returns the number of characters (before NULLNULL) in string ) in string ss
1 /* Fig. 8.37: fig08_37.c
2 Using strerror */
3 #include <stdio.h>
4 #include <string.h>
5
6 int main()
7 {
8 printf( "%s\n", strerror( 2 ) );
9 return 0;
10 }
No such file or directory
1. Function call1. Function call
2. Print2. Print
Program OutputProgram Output
Dale Roberts
Comparing StringsComparing StringsA useful operation is the comparison of two strings. Two strings are related in the A useful operation is the comparison of two strings. Two strings are related in the same three basic ways as number values. One string is either less than, equal to, or same three basic ways as number values. One string is either less than, equal to, or greater than the other. String comparison is usually based on the positions of the greater than the other. String comparison is usually based on the positions of the characters in the character set. characters in the character set. Scanning along both strings and comparing corresponding characters establish the Scanning along both strings and comparing corresponding characters establish the relationship between two strings. The strings are equal as long as corresponding relationship between two strings. The strings are equal as long as corresponding characters are equal. If two characters are different, the comparisons are based on characters are equal. If two characters are different, the comparisons are based on their relative order in the character set. The character whose code is less belongs to their relative order in the character set. The character whose code is less belongs to the lesser string. the lesser string. Ex. Ex. “abcd” < “abcz”“abcd” < “abcz”If the two strings are of different length, but identical up to the end of the shorter one, If the two strings are of different length, but identical up to the end of the shorter one, then the shorter string is the lesser of the two:then the shorter string is the lesser of the two:Ex. Ex. “abc” < “abcd”“abc” < “abcd”If the two strings are of different length and consist of Upper and lowercase letters, If the two strings are of different length and consist of Upper and lowercase letters, Upper case letters come before lower case letter and a blank has a lower value than Upper case letters come before lower case letter and a blank has a lower value than all other letters.all other letters.Ex.Ex. “AZZZ” < “Aaaah”“AZZZ” < “Aaaah”Below is an example of a comparison of strings that contain blanks. Scanning along Below is an example of a comparison of strings that contain blanks. Scanning along both strings and comparing corresponding characters, you see the strings are equal both strings and comparing corresponding characters, you see the strings are equal for the first two characters. You then compare the blank and the t; you then reach for the first two characters. You then compare the blank and the t; you then reach the conclusion below.the conclusion below.Ex.Ex. “hi there” < “hit a ball”“hi there” < “hit a ball”
Dale Roberts
Comparison FunctionsComparison Functions
Comparing stringsComparing stringsComputer compares numeric ASCII codes of characters Computer compares numeric ASCII codes of characters in stringin string
Appendix D has a list of character codesAppendix D has a list of character codes
int strcmp( const char *s1, const char *s2 );int strcmp( const char *s1, const char *s2 );
Compares string Compares string s1s1 to to s2s2
Returns a negative number if Returns a negative number if s1 < s2s1 < s2, zero if , zero if s1 == s2s1 == s2 or a positive number if or a positive number if s1 > s2s1 > s2
int strncmp( const char *s1, const char *s2,int strncmp( const char *s1, const char *s2,
size_t n );size_t n );
Compares up to Compares up to nn characters of string characters of string s1s1 to to s2s2
Returns values as aboveReturns values as above