1/5
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Strings
not first class data types in C (like int or float)
really just character (char) arrays
have a fixed maximum length
can and often are indexed like arrays (from 0)
need ‘terminating’ with an end of string marker (hidden character \0, the ASCII NUL character)
char z[] = "hello";
z[0] is ‘h’
z[5] is zero ‘\0’
Printing Strings
using %s
printf("You typed %s\n", answer);
Assuming ‘answer’ is either a char array or a pointer to a char
char *answer = "hello";
char answer[] = "hello";
Get Strings
using %s
char answer[20]; /*max length including \0 is
20!*/
scanf("%s", answer);
Comparing Strings
compare the pointers to the locations not the actual data
strcmp()
compares 2 strings and returns -1, 0, 1 (less, equal, greater)
char *password = "pass123";
//...
if (strcmp(password, "pass123") == 0 ||
strcmp password, "secret) == 0)
printf("Yes\n");
In <string.h>
int strlen(char *)/*find the length of string
s*/
char *strchr(char , int)/*find a character
within a string (pointer or NULL)*/
strcat(char *d, char *s)//append string s to d
strcpy(char *d, char *s)//copy string s to d