Declaring a string:
char str_var[20]; |
Initializing a string:
char str_var[20] = "Text goes here"; |
| T | e | x | t | g | o | e | s | h | e | r | e | \0 | ? | ? | ? | ? | ? |
char days_week[7][10] = {"Monday", "Tuesday", "Wednesday", Thursday",
"Friday", "Saturday", "Sunday"};
|
Example:
printf("__%-10s__%10s__\n","Text", "Text2");
|
Results:
__Text __ Text2__ |
Example:
char astring[20];
int numb;
scanf("%s", astring);
scanf("%d", &numb);
|
| Function | Library | Description |
| strcpy(s1, s2) | string.h | Copies the value of s2 into s1 |
| strncpy(s1, s2, n) | string.h | Copies n characters of s2 into s1. Does not add a null. |
| strcat(s1, s2) | string.h | Appends s2 to the end of s1 |
| strncat(s1, s2, n) | string.h | Appends n characters of s2 onto the end of s1 |
| strcmp(s1, s2) | string.h | Compared s1 and s2 alphabetically; returns a negative value if s1 should be first, a zero if they are equal, or a positive value if s2 sbould be first |
| strncmp(s1, s2) | string.h | Compares the first n characters of s1 and s2 in the same manner as strcmp |
| strlen(s1) | string.h | Returns the number of characters in s1 not counting the null |
Example:
char lastname[20]; char name[10] = "Joe Bob"; /* extract the last name into "lastname" */ strncpy(lastname, &name[4], 3); lastname[3] = '\0'; |