C Strings Made Easy: Declaration, Input, Output, and Library Functions
What is a String in C?
A string in C is a contiguous sequence of characters terminated by the null character (\0). Although the language does not have a dedicated string type, a string is usually represented as an array of char values. The compiler automatically appends the null terminator when you initialize a string literal.
"Welcome to the world of programming!"
The standard library header <string.h> offers a wealth of functions for manipulating strings efficiently.
Declaring and Initializing Strings
Because C treats a string as a character array, you must specify the array size. The size defines the maximum number of characters (excluding the null terminator) that can be stored.
char string_variable_name[array_size];
Typical declarations:
char first_name[15]; /* holds up to 14 characters + \0 */ char last_name[15];
When you provide an initializer, the compiler counts the characters and automatically adds the null terminator. The array size may be omitted if you give an initializer.
char first_name[15] = "ANTHONY";
char first_name[] = "NATHAN"; /* size inferred */
char string3[6] = {'h','e','l','l','o','\0'}; /* explicit terminator */
Reading Strings from the User
Input functions vary in safety and behaviour:
scanf("%s", name)reads until whitespace but is vulnerable to buffer overflows.gets()reads an entire line but is unsafe and removed from C11.fgets(name, size, stdin)reads up tosize-1characters, leaving room for the null terminator.
Example using fgets:
#include <stdio.h>
int main() {
char name[50];
printf("Enter your full name: ");
fgets(name, sizeof(name), stdin);
printf("Your name is %s", name);
return 0;
}
Printing Strings
The classic way to display a string is printf("%s", name);. Two convenient alternatives are:
fputs(name, stdout)– writes directly to the output stream.puts(name)– writes the string followed by a newline.
Example with puts:
#include <stdio.h>
int main() {
char greeting[] = "Hello, world!";
puts(greeting);
return 0;
}
The String Library (<string.h>)
Commonly used functions:
| Function | Description |
|---|---|
| strlen | Returns the length of a string (excluding the null terminator). |
| strcat | Appends one string to another. |
| strcmp | Compares two strings lexicographically. |
| strcpy | Copies a string. |
| strncmp | Compares up to n characters. |
| strncpy | Copies up to n characters. |
| strchr | Finds the first occurrence of a character. |
| strrchr | Finds the last occurrence of a character. |
| strstr | Finds a substring. |
| strncat | Concatenates up to n characters. |
| strlwr | Converts to lower case (non‑standard). |
| strupr | Converts to upper case (non‑standard). |
| strrev | Reverses a string (non‑standard). |
Illustrative program:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = " World!";
char result[40];
/* Comparison */
if (strcmp(str1, str2) == 0)
puts("Strings are equal");
else
puts("Strings are not equal");
/* Concatenation */
strcat(str1, str2); // str1 now contains "Hello World!"
printf("Concatenated: %s\n", str1);
/* Length */
printf("Length of str1: %zu\n", strlen(str1));
/* Copy */
strcpy(result, str1);
printf("Copied string: %s\n", result);
return 0;
}
Converting a String to a Number
Standard conversions:
atoi– converts toint.atof– converts todouble.atol– converts tolong.
Example with atoi:
#include <stdio.h>
#include <stdlib.h>
int main() {
char number_str[20];
printf("Enter a number: ");
fgets(number_str, sizeof(number_str), stdin);
int num = atoi(number_str);
printf("You entered %d\n", num);
return 0;
}
Key Takeaways
- A string is a sequence of characters stored in a
chararray terminated by \0. - Declare the array size before use, or let the compiler infer it when initializing.
- Use
fgetsfor safe input; avoidgetsandscanf("%s")without bounds checking. - Leverage
<string.h>for robust string operations. - Convert string numbers with
atoi,atof, oratolto avoid runtime errors. - Remember that string literals are read‑only; modifying them leads to undefined behaviour.
C Language
- C Programming Strings: Mastering Declaration, Initialization, and I/O
- Master Python Strings: Creation, Formatting, and Manipulation
- Mastering Java Strings: Creation, Methods, and Best Practices
- Java String length() Method: How to Get a String’s Size (Example)
- Mastering Java's split() Method: A Practical Guide with Code Examples
- Python Variables: Declaring and Managing String Types
- C Strings: How Null-Terminated Character Arrays Work
- Mastering C++ Strings: C-Style vs std::string
- Mastering Strings in C#: Best Practices & Tips
- Mastering Python Strings: Creation, Access, and Manipulation