The C language provides no explicit support for strings in the language itself. The string-handling functions are implemented in libraries. String I/O operations are implemented in <stdio.h> (puts , gets, etc). A set of simple string manipulation functions are implemented in <string.h>, or on some systems in <strings.h>.
The string library (string.h or strings.h) has some useful functions for working with strings, like strcpy, strcat, strcmp, strlen, strcoll, etc. We will take a look at some of these string operations.
Important: Don’t forget to include the library string.h (or on some systems strings.h) if you want to use one of these library functions.
strcpy
This library function is used to copy a string and can be used like this: strcpy(destination, source). (It is not possible in C to do this: string1 = string2). Take a look at the following example:
str_one = "abc";
str_two = "def";
strcpy(str_one , str_two); // str_one becomes "def"
Note: strcpy() will not perform any boundary checking, and thus there is a risk of overrunning the strings.
strcmp
This library function is used to compare two strings and can be used like this: strcmp(str1, str2).
- If the first string is greater than the second string a number greater than null is returned.
- If the first string is less than the second string a number less than null is returned.
- If the first and the second string are equal a null is returned.
Take look at an example:
printf("Enter you name: ");
scanf("%s", name);
if( strcmp( name, "jane" ) == 0 )
printf("Hello, jane!\n");
Note: strcmp() will not perform any boundary checking, and thus there is a risk of overrunning the strings.
strcat
This library function concatenates a string onto the end of the other string. The result is returned. Take a look at the example:
printf("Enter you age: ");
scanf("%s", age);
result = strcat( age, " years old." ) == 0 )
printf("You are %s\n", result);
Note: strcat() will not perform any boundary checking, and thus there is a risk of overrunning the strings.
strlen
This library function returns the length of a string. (All characters before the null termination.) Take a look at the example:
name = "jane";
result = strlen(name); //Will return size of four.
memcmp
This library function compares the first count characters of buffer1 and buffer2. The function is used like this: memcmp(buffer1,buffer2). The return values are as follows:
- If buffer1 is greater than buffer2 a number greater than null is returned.
- If buffer1 is less than buffer2 a number less than null is returned.
- If buffer1 and buffer2 are equal a null is returned.