String in C
In C programming, a string is a sequence of characters stored in an array. In C, strings are represented as null-terminated arrays of characters, where the null character ('\0') marks the end of the string. C does not have a built-in string data type like some other programming languages, so strings are typically manipulated using character arrays.
Here are some key points about strings in C:
1. String Declaration
- Strings in C are declared as character arrays with an additional element to store the null character ('\0').
- The array size should be large enough to accommodate the string characters plus the null character.
Syntax:
char string_name[size];
Example:
char name[20]; // Declaration of a character array to store a string of up to 19 characters
2. String Initialization:
- Strings can be initialized during declaration or assigned later using the strcpy() function.
- To initialize a string during declaration, you enclose the characters within double quotes.
Syntax:
char string_name[] = "string_value";
Example:
char greeting[] = "Hello, world!"; // Initialization of a string during declaration
3. String Input:
- You can read a string from the user using the scanf() function or the gets() function (although gets() is considered unsafe).
Example using scanf()
char name[20];
printf("Enter your name: ");
scanf("%s", name); // Reads a string from the user and stores it in the name array
4. String Output:
- You can print a string using the printf() function or the puts() function.
Example using printf():
char name[] = "John";
printf("Hello, %s!\n", name); // Output: Hello, John!
Example using puts():
char name[] = "John";
puts(name); // Output: John
String Manipulation:
- Strings can be manipulated using various library functions from the
header. - Common string functions include strlen(), strcpy(), strcat(), strcmp(), and others.
#include <string.h>
char source[] = "Hello";
char destination[20];
strcpy(destination, source); // Copies the content of source into destination
strcat(destination, " world!"); // Concatenates " world!" to destination
int length = strlen(destination); // Gets the length of the string in destination
printf("%s\n", destination); // Output: Hello world!
printf("Length: %d\n", length); // Output: Length: 12
Strings in C are a fundamental and widely used data type. They allow you to work with sequences of characters, perform string manipulation operations, and interact with input/output functions for textual data. However, it's important to handle strings carefully to avoid buffer overflow issues and ensure proper null-termination.