120 likes | 217 Views
240-222 Computer Programming Techniques Semester 1, 1998. 10-1. Strings Chapter 8-1. Objectives of these slides: to discuss string and file functions for the project. Overview:. 1. strstr 2. sscanf 3. atoi 4. fgets. 1. strstr. char * strstr (const char *s1, const char *s2)
E N D
240-222 Computer Programming TechniquesSemester 1, 1998 10-1. StringsChapter 8-1 Objectives of these slides: to discuss string and file functions for the project
Overview: 1. strstr 2. sscanf 3. atoi 4. fgets
1. strstr char *strstr(const char *s1, const char *s2) • Locates the first occurrence in string s1 of string s2. • If the string is found, a pointer to the string in s1 is returned. Otherwise a NULL pointer is returned.
Use: char *string1 = “abcdefabcdef”; char *string2 = “def”; printf(“%s%s\n%s%s\n\n%s\n%s%s\n”, “string1 =“, string1, “string2 =“, string2, “The remainder of string1 beginning with the”, “first occurrence of string2 is:, strstr(string1, string2));
Output: string1 = abcdefabcdef string2 = def The remainder of string1 beginning with the first occurrence of string2 is: defabcdef
2. sscanf int sscanf(char *s, const char *format, …) • Equivalent to scanf except the input is read from the array s instead of reading from the keyboard.
Use: char s[] = “31298 87.375”; int x; float y; sscanf(s, “%d%f”, &x, &y); printf(“%s\n%s6d\n%s%8.3f\n”, “The values stored in character array s are:”, “Interger:”, x, “Float:”, y);
Output: The values stored in character array s are: Integer: 31298 Float: 87.375
3. atoi int atoi(const char *nptr) • Converts the string nptr to int. long atol(const char *nptr) • Converts the string nptr to long int. continued
Use: int i; i = atoi(”2593"); printf(”%s%d\n%s%d\n”, “The string \”2593\” converted to int is “, i, “The converted value minus 593 is “, i - 593);
Output: The string “2593” converted to int is 2593 The converted value minus 593 is 2000
4. Other functions fgets • Reads a line from a specific file. rewind • Causes the program to reposition the file position pointer for the specified file to the beginning of the file