240-222 computer programming techniques semester 1, 1998
DESCRIPTION
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) - PowerPoint PPT PresentationTRANSCRIPT
240-222 CPT: Strings/10 1
240-222 Computer Programming Techniques240-222 Computer Programming TechniquesSemester 1, 1998Semester 1, 1998
Objectives of these slides:– to discuss string and file functions for the
project
10-1. StringsChapter 8-1
240-222 CPT: Strings/10 2
Overview:Overview:
1. strstr
2. sscanf
3. atoi
4. fgets
240-222 CPT: Strings/10 3
1. strstr1. 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.
240-222 CPT: Strings/10 4
Use: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));
240-222 CPT: Strings/10 5
Output:Output:
string1 = abcdefabcdef
string2 = def
The remainder of string1 beginning with the
first occurrence of string2 is: defabcdef
240-222 CPT: Strings/10 6
2. sscanf2. 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.
240-222 CPT: Strings/10 7
Use: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);
240-222 CPT: Strings/10 8
Output:Output:
The values stored in character array s are:
Integer: 31298
Float: 87.375
240-222 CPT: Strings/10 9
3. atoi3. 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
240-222 CPT: Strings/10 10
Use: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);
240-222 CPT: Strings/10 11
Output:Output:
The string “2593” converted to int is 2593
The converted value minus 593 is 2000
240-222 CPT: Strings/10 12
4. Other functions4. 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