120 likes | 130 Views
INC 161 , CPE 100 Computer Programming. Lecture 7 String. Characters. Characters such as letters and punctuation are stored as integers according to a certain numerical code, such as ASCII code that ranges from 0 to 127 and only requires 7 bits to represent it.
E N D
INC 161 , CPE 100Computer Programming Lecture 7 String
Characters • Characters such as letters and punctuation are stored as integers according to a certain numerical code, such as ASCII code that ranges from 0 to 127 and only requires 7 bits to represent it. • Character constant is an integral value represented as a character in single quotes. ’a’ represents the integer value of a.If ASCII code is used to represent characters, the ASCII value for ’a’ is 97. • Using char to declare a character variable. char c = ’a’; // the same as char c = 97;
Character Input and Output • Functions in <stdio.h> • int getchar(void); Reads the next character from the standard input. • int putchar(int c); Print the character stored in c • int scanf(const char *, …); with conversion specifier c. char c; scanf(“%c”, &c); • int printf(char *, …); with conversion specifier c. char c=’a’; printf(“%c”, c);
Strings • Strings are series of characters treated as a single unit • Can include letters, digits, and certain special characters (*, /, $) • String literal (string constant) - a sequence of multi-byte characters enclosed in double quotes • "Hello" • Declare a string as a character array or a variable of type char * char str1[7] = {’S’, ’t’, ’r’, ’i’, ’n’, ’g’, ’\0’}; char str2[ ] = {’S’, ’t’, ’r’, ’i’, ’n’, ’g’, ’\0’}; char str3[ ] = “String”; char *strPtr = “String”; • String must have an end character 0 or ‘\0’ or NULL
char a[10] = “Hello” ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ Don’t care what it stores End Character
String Input and Output • Functions in <stdio.h>
Example 2 : sprintf, sscanf #include <stdio.h> main() { char str[40]; int a = 123, b = 0; printf("Please input a string.\n"); scanf(“%s”,str); printf(“The input is: ”); printf(“%s”,str); sprintf(str,“The value of a %d\n”,a); printf(“%s”,str); sscanf(str,“The value of a %d\n”,&b); printf(“After sscanf b is %d\n”,b); }
String Manipulation • Header file string.h has functions to • Determining string length strlen • Copying strings strcpy • Appending strings strcat • Comparing strings strcmp • Searching strings • Tokenizing strings
Example 3:strcmp, strcpy, strcat #include <stdio.h> #include <string.h> main() { char s1[10]="ABCD", s2[10]="ABCD", s3[10]="abcd"; printf("strcmp(s1, s2) = %d\n", strcmp(s1, s2)); printf("strcmp(s1, s3) = %d\n", strcmp(s1, s3)); printf("strcmp(s3, s1) = %d\n", strcmp(s3, s1)); strcpy(s1, s3); printf("s1 = %s\n", s1); strcpy(s1, "1234"); printf("s1 = %s\n", s1); strcat(s1, "Hello"); printf("s1 = %s\n", s1); printf("strlen(s1) = %d\n", strlen(s1)); }
Output: strcmp(s1, s2) = 0 strcmp(s1, s3) = -1 strcmp(s3, s1) = 1 s1 = abcd s1 = 1234 s1 = 1234Hello strlen(s1) = 9