Updated September 4, 2023
Introduction to C String Functions
String functions form the backbone of any programming language as it tells you how a particular language handles strings. Handling strings means that your programming language should be efficient enough to modify the string that you have and perform the required changes. Many C string functions exist to simplify string handling, allowing you to call and implement them in your code without the need for manual coding.
There are two kinds of functions: the library functions and the second is the custom-based functions. In the latter, you can create your part or a method and use them in your code as and when you like it. Normally, these functions are identified with empty parentheses. In this C string function article, you will learn how to manipulate strings using C functions along with examples such as puts(), gets(), strlen(), etc. All string functions in C are available in the standard library “string. h”.
The creators of the C language designed it for developing system-based applications that interact directly with hardware devices like kernels, drivers, etc. Basically, it is for all system-related communication as it is a low-level, system-friendly programming language. The C programming language serves as the foundation for all programming languages, including procedural, mid-level, and structured ones. It is specific to a machine, i.e., machine-dependent and comparatively faster to run. It isn’t easy to understand, though, as it requires basic programming knowledge and mindset.
Table of Contents
- Introduction to C String Functions
- List of C String Functions with Examples
- Benefits of Using C String Functions
- Error Handling and Input Validation in C String Functions
Key Takeaways
- The C Standard Library contains functions for manipulating strings, which are collections of characters that end in the null character (‘0’).
- With the help of crucial functions like strlen, strcpy, strcat, and strcmp, you can calculate the length of a string, copy it, concatenate it, and compare strings.
- Handling null-terminated strings correctly is essential to prevent buffer overflows and unpredictable behavior.
- C string functions are effective and often utilized for text processing and modification tasks. To prevent frequent hazards like buffer overflows and guarantee the security of their code, developers need to take care.
List of C String Functions with Examples
The string function is easy to use. Here, we will discuss how to use string functions in C programming with the help of examples.
1. printf()
A standard library function in C called printf() produces formatted data to the console or terminal. It is a component of the stdio.h (standard input-output header) library stands for “print formatted”. The function is adaptable and flexible for different output requirements, allowing you to show data in a specific format by utilizing format specifiers.
Syntax:
int printf(const char *format, ...);
Example:
#include<stdio.h>
int main()
{
printf("Name: Antonio");
}
Output:
2. gets()
To read a line of text from the standard input (the keyboard) and store it as a string in the C language, use the standard library function gets(). Remember that the gets() function is considered dangerous and has been banned since the C11 standard due to potential buffer overflow flaws. It is advisable to use safer substitutes like fgets() instead.
Syntax:
char *gets(char *str);
Example:
#include <stdio.h>
int main() {
char add[30]; // Declare a character array to store the input
printf("Enter your add: ");
gets(add); // Read the input from the user
printf("I live in, %s!\n", add); // Display the input
return 0;
}
Output:
3. puts()
A string can be written to the standard output (often the console or terminal) using the C standard library function puts(). Text messages or strings are frequently displayed on screens using this technique.
Syntax:
int puts(const char *str);
Example:
#include<stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name);
puts(name);
}
Output:
4. char
A string is a group of characters stored in an array and terminated by the null character, denoted by the symbol ‘0’ in the C programming language. Several built-in functions in C make it simple to work with strings. The header file “string.h” contains declarations for these functions, which are a part of the common C library.
Syntax:
char array_name[array_size];
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Welcome";
int length = strlen(str);
printf("Size of the string is: %d\n", length);
return 0;
}
Output:
5. scanf()
The C function scanf() reads formatted input from standard input, often the keyboard, and saves the information in variables. It enables you to read various data from a file or the user, including characters, strings, numbers, etc.
A format string describing the anticipated input format must be provided when utilizing the scanf() function. Conversion specifiers in the format string begin with the % symbol. A pointer to the variable where the data should be put follows each conversion specifier corresponding to the type of data you want to read.
Syntax:
int scanf(const char *format, ...);
Example:
#include <stdio.h>
int main() {
char name[25]; // Assuming the name will be no longer than 22 characters
printf("Enter your name: ");
scanf("%22s", name);
printf("Hey, %s!\n", name);
return 0;
}
Output:
6. strcpy(s1, s2)
To transfer the content of one string (s2) to another string (s1), use the C string function strcpy(s1, s2). The function is listed in the header file “string.h” and is a component of the common C library. The destination string (s1) must have enough room to include the source string (s2) contents and the null terminator.
Syntax:
char *strcpy(char *dest, const char *src);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char s1[24];
char s2[] = "Welcome, Back!";
strcpy(s1, s2);
printf("s1: %s\n", s1);
printf("s2: %s\n", s2);
return 0;
}
Output:
7. strcat()
To concatenate (append) one string to the end of another string, use the C string method strcat(). By combining two character arrays with null terminations, you can extend the destination string by the contents of the source string. The function is listed in the header file “string.h” and is a component of the standard C library.
Syntax:
char *strcat(char *dest, const char *src);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Welcome ";
char str2[] = "Back!";
strcat(str1, str2); // Concatenate str2 at the end of str1
printf("Concatenated string: %s\n", str1);
return 0;
}
Output:
8. strlen()
To get the length of a null-terminated character array, generally called a C string, use the strlen() method. It counts the characters in the string until it encounters the null terminator (‘0’). The function is listed in the header file “string.h” and is a component of the common C library.
Syntax:
size_t strlen(const char *str);
Example:
#include <stdio.h>
#include <string.h>
int main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
}
Output:
9. strrev()
In C, a null-terminated string can be reversed in place using the strrev() method. It is described in the header file string.h and is a component of the C standard library. The sole argument for the function is a pointer to the null-terminated string that needs to be reversed. The original string will be reversed when the function completes, and no further memory allocation is made.
Syntax:
Like strlen(), the strrev() function is not a part of the standard C library. You usually have to build your code or use functions from the standard library to reverse a string in C.
Example:
#include<stdio.h>
#include<string.h>
void strrev(char* str) {
int start = 0;
int end = strlen(str) - 1;
char temp;
while (start < end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char str[] = "educba";
printf("Original string: %s\n", str);
strrev(str);
printf("Reversed string: %s\n", str);
return 0;
}
Output:
10. strcmp()
To compare two null-terminated strings lexicographically in C, use the strcmp() function. It is described in the header file string.h and is a component of the C standard library. Two pointers to the two strings that need to be compared are provided as the function’s two arguments.
Expression | Returns |
str 1 > str 2 | It returns a Positive integer |
str1 < str 2 | It returns Negative |
str 1 = str 2 | It returns Zero |
Syntax:
int strcmp(const char *str1, const char *str2);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "cat";
char str2[] = "dog";
int result = strcmp(str1, str2);
if (result < 0) {
printf("%s comes before %s\n", str1, str2);
} else if (result > 0) {
printf("%s comes after %s\n", str1, str2);
} else {
printf("%s is equal to %s\n", str1, str2);
}
return 0;
}
Output:
11. Strncmp
Strncmp is an acronym for “string compare up to n characters.” Up to a specified maximum number of characters (n), or until it comes across a null terminator (‘0’) in either string, it compares two C strings character by character.
Expression | Returns |
string 1(first n characters) > string 2(first n characters) | It returns a Positive integer |
string 1(first n characters) < string 2(first n characters) | It returns Negative |
string 1(first n characters) = string 2(first n characters) | It returns Zero |
Syntax:
int strncmp(const char *str1, const char *str2, size_t n);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "mango";
char str2[] = "marshmello";
int result = strncmp(str1, str2, 2); // Compare the first 2 characters
if (result == 0) {
printf("The first 2 characters of str1 and str2 are equal.\n");
} else if (result < 0) {
printf("str1 is less than str2.\n");
} else {
printf("str1 is greater than str2.\n");
}
return 0;
}
Output:
12. Strcasecmp
strcasecmp compares strings case-insensitively and is frequently encountered in Unix-like operating systems. It may be accessible as stricmp in some systems. Uppercase and lowercase characters are treated equally when comparing two strings character by character.
If | Returns |
str1 < str2 | It returns Less than 0 |
str1 = str2 (ignoring case) | It returns 0 |
str1 > str2 | It returns Greater than 0 |
Syntax:
int strcasecmp(const char *str1, const char *str2);
Example:
#include <stdio.h>
#include <strings.h>
int main() {
char str1[] = "Welcome";
char str2[] = "welcome";
int result = strcasecmp(str1, str2);
if (result == 0) {
printf("str1 and str2 are equal (case-insensitive).\n");
} else if (result < 0) {
printf("str1 is less than str2 (case-insensitive).\n");
} else {
printf("str1 is greater than str2 (case-insensitive).\n");
}
return 0;
}
Output:
13. strupr()
The strupr() function is a C string function for “string uppercase.” It converts all the lowercase letters in a null-terminated string to their corresponding uppercase equivalents. The function takes a single argument, a pointer to the null-terminated string you want to modify. It iterates through each character in the string and changes any lowercase letters to uppercase, leaving the non-alphabetic characters unchanged. It’s important to note that the strupr() function modifies the original string in place and does not create a new string.
Syntax:
char *strupr(char *str);
Example:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void strToUpper(char *str) {
int i = 0;
while (str[i]) {
str[i] = toupper(str[i]);
i++;
}
}
int main() {
char myString[] = "Come, Back!";
printf("Original string: %s\n", myString);
strToUpper(myString);
printf("Uppercase string: %s\n", myString);
return 0;
}
Output:
14. strlwr()
The strlwr function is a C string manipulation function that converts all the characters in a given string to lowercase. It stands for “string lower” and is typically used to ensure that the characters in a string are in lowercase format. The function takes a single argument, a pointer, to the string you want to convert to lowercase. Then, it modifies the characters in that string in place, changing any uppercase characters to their lowercase equivalents. It’s important to note that strlwr is not a standard C library function and may not be available in all C environments. The tolower function in a loop can provide better portability and control over character case conversions.
Syntax:
char *strlwr(char *str);
Example:
#include <stdio.h>
#include <ctype.h>
void toLowercase(char *str) {
while (*str) {
*str = tolower(*str);
str++;
}
}
int main() {
char text[] = "See You!";
printf("Original: %s\n", text);
toLowercase(text);
printf("Lowercase: %s\n", text);
return 0;
}
Output:
15. sizeof()
The sizeof() operator in C calculates the size in bytes of a data type or variable; it is not a true function. It determines the amount of memory required for basic data types, arrays, and structures.
Syntax:
sizeof(data_type);
Example:
#include <stdio.h>
int main()
{
int arr[] = { 8, 0, 2, 5, 9, 4 };
printf("Total Number of elements in the array:%lu ",
sizeof(arr) / sizeof(arr[0]));
return 0;
}
Output:
16. strchr()
The strchr() function in C locates the first instance of a particular character (provided as its second argument) in a C-style null-terminated string (provided as its first argument). It is a component of the string.h header. If the character cannot be found, the function produces a NULL pointer; otherwise, it returns a pointer to the first instance of the character in the string.
Syntax:
char *strchr(const char *str, int character);
Example:
#include <stdio.h>
#include <string.h>
int main () {
const char str[] = "http://www.google.com";
const char ch = '.';
char *ret;
ret = strchr(str, ch);
printf("String after |%c| is - |%s|\n", ch, ret);
}
Output:
17. strstr()
To locate the first instance of a substring within a C-style null-terminated string, use the strstr() function, which is a component of the string.h header. If the substring cannot be found, the function produces a NULL pointer; else, it returns a pointer to the first instance of the substring in the string.
Syntax:
char *strstr(const char *str1, const char *str2);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Good, Bye!";
char substring[] = "Bye";
char *result;
result = strstr(str, substring);
if (result != NULL) {
printf("Substring found at index: %ld\n", result - str);
printf("Substring: %s\n", result);
} else {
printf("Substring not found.\n");
}
return 0;
}
Output:
Benefits of Using C String Functions
- Simplified String Manipulation: To perform frequent activities on strings, such as copying, concatenating, comparing, searching, and tokenizing, string functions offer a collection of predefined operations. This spares you from manually managing these activities by creating complex and error-prone code.
- Efficiency and Performance: String functions frequently optimize performance by employing effective memory management strategies and efficient algorithms. They can process strings quickly and effectively because their implementation minimizes overhead and maximizes speed.
- Code Reusability: Using string functions, you can build reusable code for various projects or circumstances. You can rely on the tried-and-true and frequently utilized string functions offered by the C standard library rather than creating the wheel from scratch.
- Standardization and Portability: String functions are portable and standardized because the C standard library includes them, making all C compilers and operating systems support them. As a result, you can easily port your code and execute it on various platforms without worrying about incompatibilities.
- Saving Time: String functions streamline the creation process by removing the need to create intricate string manipulation methods. By doing this, you can save time and effort and concentrate on the logic or functionality of other parts of your program.
- Readability and Maintainability: Using string functions improves code readability because their names are evocative and clearly indicate their intended purpose. As a result, other programmers will find it simpler to comprehend and maintain your code.
Error Handling and Input Validation in C String Functions
Writing secure and reliable C string functions requires error management and input validation. If used carelessly, C string methods that operate on null-terminated character arrays (strings) can easily result in errors, crashes, or security flaws.
The handling of errors and input validation in C string functions are as follows:
1. Error Handling
Error handling involves identifying and responding to errors that may occur while executing a C string function. Different causes, such as improper input, insufficient memory, or boundary violations, might lead to these failures. The program responds gracefully to unforeseen circumstances when it handles errors properly, reducing the risk of program crashes and offering instructive feedback to users or other program components.
In C string functions, common methods for managing errors include:
- Return Values: To describe the type of error, functions may return specific error codes. A function might, for instance, return 0 upon success and -1 upon failure.
- Using Errno: People frequently use the global variable errno to identify specific error conditions. When there is an overflow or underflow, some string functions, like strtol, strtod, etc., change errno to ERANGE.
- Setting Error Flags: Functions can notify error circumstances using external flags. For instance, a unique error_flag variable might be set to true when an error occurs.
- Printing Error Messages: In some circumstances, functions use the fprintf(stderr,…) function to print error messages directly to the standard error stream. This allows users and developers to grasp the error’s root cause better.
Input Validation
Input validation examines user-provided data (input) to ensure it complies with specific requirements and is secure for usage with the C string functions. It is essential to avoid buffer overflows, format string flaws, and other security problems that malicious users could exploit.
In C string functions, common methods for input validation include:
- Length Verification: To avoid buffer overflows, functions should verify that the input string length is within acceptable bounds before performing any string operations. You can copy a few characters using functions like strncpy to prevent potential problems.
- Character Validation: Verify that only the expected characters are present in the input using character validation. A function should verify that the string only contains numeric characters, for instance, if it expects the string to reflect a legitimate number.
- Escape Sequences: Handle escape sequences correctly when processing user input to avoid undesired behavior.
- Memory Allocation: If a function dynamically allocates memory, it should verify that the memory allocation was successful before performing string operations.
You can increase the dependability and security of your C string functions while lowering the chance of errors and vulnerabilities by providing robust error handling and input validation.
Conclusion
There are many pre-built library functions in the C programming language, and it also allows you to create your custom function. Even if you do not want to create a function, you can write a piece of code corresponding to your requirement, but using functions will make your job a lot easier and more convenient.
FAQs
Q1. How can I concatenate two strings in C?
Ans: The strcat() function can join two strings together. The source string is added to the final string.
Q2. What function should I use to read a line of text from the user?
Ans: The fgets() function can read one line of text from the user. It reads characters from the input stream until a newline or the specified maximum number of characters is reached.
Q3. Are C string functions safe from buffer overflows?
Ans: No, most built-in C string functions, including strcpy() and strcat(), are not protected against buffer overflows. To avoid potential buffer overflow issues, it is advised to use safer alternatives like strncpy() and strncat() and check the buffer size.
Recommended Articles
We hope that this EDUCBA information on “C String Functions” was beneficial to you. You can view EDUCBA’s recommended articles for more information.