Programming Languages -1 (Introduction to C) strings Instructor: M.Fatih AMASYALI
2 The Data Type char The data type char can be thought of as either a character or an integer. Typically, a char has a value printf( “%c”, ‘a’ ); /* a is printed */ printf( “%d”, ‘a’ ); /* 97 is printed */ printf( “%c”, 97 ); /* a is printed */ ‘a’ == 97, ‘b’ == 98, …, ‘z’ == 112 ‘A’ == 65, ‘B’ == 66, …, ‘Z’ = 90 ‘0’ == 48, ‘1’ == 49, …, ’9’ == 57 ‘&’ == 38, ‘*’ == 42, …
3 Codes corresponding to characters For use inside in single-quotes, or double- quotes, for instance in passing a string to printf Character Escape Sequence Integer Value Newline \n 10 Backslash (\) \\ 92 Single quote \’ 39 Double quote \” 34 Horizontal tab \t 9 Question Mark \? 63 Null Character \0 0
4 Strings Strings are one-dimensional arrays of type char. Hence, they have type char *. By convention, a string in C is terminated by \0 (null character); thus it needs space equal to the size of string +1 A string constant is treated by the compiler as a pointer; also space in memory is allocated for storing the characters. char *p = “abc”; printf(“%s %s\n”, p, p+1 ); /* prints abc bc */ printf(“%c”,"abc”[1]); /* prints b */ printf(“%c”,*(“abc” + 2)); /* prints c */ CornellUni\
5 Example: “Double” printing #include void new_print( char *s ) { int i; for( i = 0; s[i] != 0; i++ ) { printf( "%c%c", s[i], s[i] ); } void main() { new_print( “Cornell" ); } All of {0, ‘\0’, NULL} are legal.
6 Strings are also char pointers #include void new_print( char *s ) { while (*s) { printf( "%c%c", *s, *s ); s++; } void main() { new_print( “Cornell" ); }
7 Example: “squeeze” function /* squeeze deletes all instances of c from s */ void squeeze( char s[], int c ) { int i, j; for( i = j = 0; s[i] != ‘\0’; i++ ) { if( s[i] != c ) { s[j] = s[i]; j++; } s[j] = ‘\0’; } Usage: char p[]="Cornell"; squeeze( p, 'o'); printf("%s\n",p);
8 String Input/Output #include #define MAXLENGTH 15 int main() { char string1[MAXLENGTH]; char string2[MAXLENGTH]; scanf("%s %s", string1, string2); printf("%s %s\n", string1, string2); return 0; }
9 Character String Declaration Declaration 1: char name[5] = “Ann”; Ann\0 0x2000 0x2004 name is 0x2000
10 Character String Declaration Declaration 1: char name[5] = “Ann”; Ann\0 0x2000 0x2004 name is 0x2000 Could have defined this as an array: char name[5] = {’A’,’n’,’n’,’\0’};
11 Character String Declaration (cont) Declaration 1: char name[5] = “Ann”; Can store at most 4 letters, because of `\0’ Ann\0 0x2000 0x2004 name is 0x2000
12 Character String Declaration (cont) Declaration 2: char name[] = “Ann”; Takes up an extra cell for ‘\0’ Ann\0 0x2000 0x2003 name is 0x2000
13 Character String Declaration (cont) Declaration 3: char *name = “Ann”; Result is “undefined” if you try to modify this string Ann\0 0x3000 0x3003 0x3000 name
14 Character String Declaration (cont) Declaration 4: char name[]; String with arbitrary length? No! Will cause an error “storage size of k isn’t known”
15 A Char in a String (cont) index 2 John\0 0x39950x399C name is 0x3995 char name[8] = “John”; name[2] = ‘X’; printf(“Name: %s\n”, name); X
16 JoXn\0 0x39950x399C name is 0x3995 output: Name: JoXn index 2 char name[8] = “John”; name[2] = ‘X’; printf(“Name: %s\n”, name); A Char in a String (cont)
17 char name1[5] = “Anne”; char name2[5] = “Dave”; name2 = name1; Common Mistake 1: Example: Error: “ISO C++ forbids assingment of arrays”
18 char *name1 = “Ann”; char *name2 = “Dave”; name2 = name1; Caution 1: Pointer Assignment Example:
19 Caution 1: Pointer Assignment Dave\0 0x39900x3994 Ann\0 0x20000x2003 0x2000 name1 0x3990 name2 char *name1 = “Ann”; char *name2 = “Dave”;
20 Caution 1: Pointer Assignment Dave\0 0x39900x3994 Ann\0 0x20000x2003 0x2000 name1 0x2000 name2 name2 = name1;
21 #include #define NAMELEN 50 /* Print a simple greeting to the user */ void Greet ( char * name ) { strcat(name, "! How are ya?"); } int main() { char user[NAMELEN]; printf("Who are you? "); scanf("%s", user); Greet(user); printf("%s\n", user); return 0; } user Jake\0
22 int main() { char user[NAMELEN]; printf("Who are you? "); scanf("%s", user); Greet(user); printf("%s\n", user); return 0; } #include #define NAMELEN 50 /* Print a simple greeting to the user */ void Greet ( char * name ) { strcat(name, "! How are ya?"); } name user Jake\0
23 int main() { char user[NAMELEN]; printf("Who are you? "); scanf("%s", user); Greet(user); printf("%s\n", user); return 0; } #include #define NAMELEN 50 /* Print a simple greeting to the user */ void Greet ( char * name ) { strcat(name, "! How are ya?"); } user Jake! How are ya?\0 name
24 int main() { char user[NAMELEN]; printf("Who are you? "); scanf("%s", user); Greet(user); printf("%s\n", user); return 0; } #include #define NAMELEN 50 /* Print a simple greeting to the user */ void Greet ( char * name ) { strcat(name, "! How are ya?"); } user Jake! How are ya?\0
25 Character-handling library functions.
26 isdigit tests if a character is a decimal digit isalpha tests if a character is a letter
27 isdigit tests if a character is a decimal digit or a letter isxdigit tests if a character is a hexadecimal digit
28
29 islower tests if a character is a lowercase letter isupper tests if a character is an uppercase letter
30 toupper and tolower convert letters to upper or lower case
31 String-Conversion Functions Conversion functions –In (general utilities library) Convert strings of digits to integer and floating-point values
32 String-conversion functions of the general utilities library.
33 atof converts a string to a double
34 atoi converts a string to an int
35 strtod converts a piece of a string to a double
36 Standard Input/Output Library Functions Functions in Used to manipulate character and string data
37 Standard input/output library character and string functions.
38 gets reads a line of text from the user
39 putchar prints a single character on the screen
40 puts prints a line of text on the screen getchar reads a single character from the user
41
42 sprintf prints a line of text into an array like printf prints text on the screen
43 sscanf reads a line of text from an array like scanf reads text from the user
44 String-manipulation functions of the string-handling library.
45 Portability Tip Type size_t is a system-dependent synonym for either type unsigned long or type unsigned int.
46 strcpy copies string x into character array y strncpy copies 14 characters of string x into character array z Note that strncpy does not automatically append a null character
47 strcat adds the characters of string s2 to the end of string s1 strncat adds the first 6 characters of string s1 to the end of string s3
48
49 Comparison Functions of the String- Handling Library Comparing strings –Computer compares numeric ASCII codes of characters in string
50 String-comparison functions of the string-handling library.
51 strcmp compares string s1 to string s2
52 strncmp compares the first 6 characters of string s1 to the first X characters of string s3
53 strcpy(string1, “Apple”); strcpy(string2, “Wax”); if (string1 < string2) { printf(“%s %s\n”, string1, string2); } else { printf(“%s %s\n”, string2, string1); } Common Mistake: Wrong Comparison
54 strcpy(string1, “Hi Mum”); strcpy(string2, “Hi Mum”); if ( strcmp(string1, string2) ) { printf(“%s and %s are the same\n”, string1, string2); } Caution 1: Not a Boolean Returns zero if the strings are the same. if ( strcmp(string1, string2) == 0)
55 char string1[100]; strcpy(string1, “Apple”); printf(“%d\n”, strlen(string1)); output: 5 Number of char-s before the `\0’ String Operation: Length
56 String-manipulation functions of the string-handling library.
57 String-manipulation functions of the string-handling library.
58 strchr searches for the first instance of character1 in string
59
60 strcspn returns the length of the initial segment of string1 that does not contain any characters in string2 String1’in, String2’deki karakterlerden hiçbirini içermeyen, ilk kısmının uzunluğu
61 strpbrk returns a pointer to the first appearance in string1 of any character from string2 String1’de, String2’deki karakterlerden herhangi birinin ilk geçtiği yerin adresi
62 strrchr returns the remainder of string1 following the last occurrence of the character c String1’in, c karakterinin son geçtiği yerden itibarenki kısmı
63 strspn returns the length of the initial segment of string1 that contains only characters from string2 String1’in, Sadece String2’deki karakterlerden oluşan ilk kısmının uzunluğu
64 strstr returns the remainder of string1 following the first occurrence of string2 String1’in, string2’nin ilk geçtiği yerden itibarenki kısmı
65 strtok “tokenizes” string by breaking it into tokens at each space Calling strtok again and passing it NULL continues the tokenizing of the previous string
66
67 Memory Functions of the String-Handling Library Memory Functions –In –Manipulate, compare, and search blocks of memory –Can manipulate any block of data Pointer parameters are void * –Any pointer can be assigned to void *, and vice versa –void * cannot be dereferenced Each function receives a size argument specifying the number of bytes (characters) to process
68 Memory functions of the string-handling library.
69 Common Programming Error 8.8 String-manipulation functions other than memmove that copy characters have undefined results when copying takes place between parts of the same string.
70 memcpy copies the first 17 characters from object s2 into object s1
71 memmove copies the first 10 characters from x[5] into object x by means of a temporary array
72 memcmp compares the first 4 characters of objects s1 and s2
73 memchr locates the first occurrence of the character r inside the first 16 characters of object s
74 memset copies the character b into the first 7 characters of object string1
75 Referance Ioannis A. Vetsikas, Lecture notes Dale Roberts, Lecture notes