Introduction to strings
In C programming, a string is a sequence of characters stored in consecutive memory locations. Each character in a string is represented using the ASCII code. C does not have a built-in string data type like some other programming languages, but instead, strings are represented as arrays of characters.
To declare and work with strings in C, you need to include the <string.h> header file, which contains various string manipulation functions.
Here's a step-by-step introduction to working with strings in C:
Declaring a string:
To declare a string, you create an array of characters. For example:
char myString[20]; // This declares a string of size 20, which can hold 19 characters plus the null terminator.
Initializing a string:
You can initialize a string at the time of declaration:
char greeting[] = "Hello, world!";
Assigning values to a string:
You can assign values to a string using the assignment operator or functions like strcpy():
char name[50];
strcpy(name, "John");
String Input:
You can read input from the user and store it in a string using functions like scanf():
char input[100];
printf("Enter your name: ");
scanf("%s", input);
String Output:
To print a string, you can use the %s format specifier with printf():
char message[] = "Welcome!";
printf("%s\n", message);
String Functions:
C provides several functions to manipulate strings in the <string.h> library. Some commonly used string functions are:
strlen(): Calculates the length of a string.
strcmp(): Compares two strings.
strcat(): Concatenates two strings.
strcpy(): Copies one string to another.
Here's an example using some of the string functions: