Sie sind auf Seite 1von 13

Character Strings

• A sequence of characters is often referred to as a character

• A string is stored in an array of type char ending with the
null character '\0 '.
Character Strings
A string containing a single character takes up 2
bytes of storage.
Character Strings vs array
Character Strings
Character vs. String
Strings in C
• No “Strings” keyword
• A string is an array of characters.
char string[] = “hello world”; OR
char *string = “hello world”;
Strings in C (continued)
• Let
– char *u = "This is another string!";
• Then
– u[0] == 'T'
u[1] == 'h'
u[2] == 'i'

u[21] == 'g'
u[22] == '!'
u[23] == '\0'
Support for Strings in C
• Most string manipulation is done through functions
in <string.h>
• String functions depend upon final '\0'
• So you don’t have to count the characters!
• Examples:–
– int strlen(char *s) – returns length of string
• Excluding final '\0'
– char* strcpy(char *dest, char *src) – Copies string
src to string dest, return dest
• dest must be big enough to hold contents of src
• src may be smaller than dest
Ex. 6: String Copy Function in <string.h>
void strcpy(char dest[], const char src[]);
//copies string src into string dest
char name1[16], name2[16];
strcpy(name1,"Chan Tai Man");
C h a n T a i M a n \0 ? ? ?

9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 \0
C h a n T a i M a n \0 9 9 \0
Example 7: strcpy in <string.h>
#include <string.h>
int main (){
char string_1[6] = "Short"; // character strings
char string_2[17] = "Have a Nice Day";
char string_3[6] = "Other";
strcpy(string_1, string_2);
return 0;
Support for Strings in C (continued)
• Examples (continued):–
– int strcmp(char *s, char *t)
• lexically compares s and t, returns <0 if s < t, >0 if
s > t, zero if s and t are identical

– char* strcat(char *s, char *ct)

• Concatenates string ct to onto end of string s, returns s
• s must be big enough to hold contents of both strings!
Character functions in C
• See <ctype.h>
• These return or false (0) or true (non-zero)
int isdigit(int c) int isalpha(int c)
int isalnum(int c)
int islower(int c) int isupper(int c)
int isspace(int c)
int ispunct(int c)
• These change case (if appropriate)
int toupper(int c) int tolower(int c)