Strings in C

Character Type: char

In C, characters are indicated by single quotes

char ch;
ch = 'a';
printf("%c\n", ch);
			

The type is char for one character

%c is the formal specifier for char

Strings in C

String

A string is an array of characters, it is indicated by double quotes:

"this is a string"

But you can't use an assignment operator to assign a string to a character array

char str[100]; //array of chars
str[4] = 'a'; //ok
str = "this is a string"; //not ok
			
Strings in C

String

A null ('\0') character is placed to mark the end of each string

this is a string\0

String functions use '\0' to locate end of string (so you don't have to pass string length as argument to the functions)

Strings in C

Initializing a String

char str[] = {'a', 'b', 'c', 'd', '\0'};
printf("%s\n", str);
			
abcd\0

Array size has exactly 5 elements

A terminating '\0' character at the end (in ASCII, char '\0' is equivalent to int 0)

Will print: "abcd"

Strings in C

Another way

char str[8] = "hello";
printf("%s\n", str);
				
hello\0  

Ok to use assignment only to initialize string

str is an array of 8 characers (but only the first 5 elements used to store the word)

A '\0' is added to the end automacically (so 6 elements in the array are occupied)

Strings in C

Better way

char str[] = "hello";
printf("%s\n", str);
				
hello\0

'\0' is added automatically to the end of str

Space is allocated automatically to hold exactly what we need( 6 locations, include '\0')

Strings in C

printf for Strings

char str = "abc123";
			

Output

Use %s to print the entire string:

printf("%s\n", str);//output abc123, '\0' is not printed
			

Use %c to print a character:

printf("%c\n", str[1]);//output: b
			
Strings in C

String input

There are several functions available

Part of the stdio.h library.

Strings in C

scanf

scanf reads up to the first white space, ignores the stuff typed in after the. Be careful when using it.

char str[10];
printf("Enter a string");
scanf("%s", str);
printf("You entered %s\n", str);
			
Strings in C

scanf safer

Use %[width]s to copy only up to a maximum number of character. But, does not append the '\0'

char str[10];
printf("Enter a string: ");
scanf("%9s", str);
printf("You entered %s\n", str);
			
Strings in C

getchar

getchar will fetch one character from the input stream

char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered %c\n", ch);
			
Strings in C

fgets

char* fgets(charArray, lengthLimit, filePtr)

fetches a whole line, up to the size litmit or when it sees a newline

It will add a '\0' at the end of string

Example

char str[10];
fgets(str, 10, stdin);//fetch from console
			

Returns a NULL if something when to wrong, otherwise a pointer to the array

Strings in C

String manipulations functions

strcpy - Copies a string

strcat - Concatenates two strings

strlen - Returns the length of a string

strcmp - Compares two strings

Strings in C

String copy (strcpy)

char[] strcpy(char dest[], const char src[]);

Copy string contents from src (2nd arg) to dest (1st arg) including '\0'

dest is changed, src unmodifined (but can do some weird things)

returns a pointer to the modified dest array

There is no error checking

If dest array is shorter than src, no errors, Weird things could happen, but no compile errors and offer no runtime errors)

Tracking these "bugs" down is very hard!

Strings in C

Safer version of string copy (strcpy)

char[] strncpy(char dest[], const char src[], int n);

Copies at most n characters from src to dest(or up to '\0')

If length of src is greater than n, copies only the first N characters

If length of src is less than N, pad the remaining elements in dest with '\0'

Does not copy the '\0' if the string length is >= N

Strings in C

Concatenation (strcat)

char[] strcat(char dest[], const char src[]);

Contents of src are added to the end of dest

dest is changed, src is not

'\0' added to the end of dest

return a pointer to dest

no bounds check (again, this is C)

Strings in C

Comparison (strcmp)

int strcmp(const char s1[], const char s2[]);

Compares 2 strings

if s1 precedes s2, return value is less than 0

if s2 precedes s1, return value is greater than 1

if s1 equal to s2, return value is 0

Comparison is based on lexicographic order (ASCII-order) - e.g 'a' < 'b'

Strings in C

Built-in functions for characters

These all return boolean(1/0)

isalnum(c): is c a alphanumeric?

isalpha(c): is c a alphabetic?

isdigit(c): is c a digit?

iscntrol(c): is c a control character?

islower(c): is c a lower case?

isuper(c): is c a upper case?

ispunct(c): is c a punctuation character, that is a printable character that is neither a space nor an alphanumeric character?

Strings in C

Converters for characters

char tolower(c)

return the character as lower case

char toupper(c)

return the character as upper case