A string is a sequence of characters stored as an array of characters, terminated by a null character ('\0'). Strings are used to represent textual data and are an essential part of C programming. The standard C library provides various functions for manipulating strings, and string handling is a fundamental skill for C programmers.
Declaring and Initializing Strings:
Strings in C can be declared and initialized in several ways:
1) Character Array:
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Alternatively, you can use a string literal for initialization:
char greeting[] = "Hello";
In this case, the size of the array is automatically determined by the length of the string literal plus one for the null character.
2) Pointer to a String:
char *greeting = "Hello";
This declares a pointer to the first character of the string literal.
String Functions in C:
C provides several standard library functions for string manipulation. Here are some commonly used functions:
strlen (String Length):
#include <string.h>
size_t length = strlen(greeting);
This function returns the length of the string, excluding the null character.
strcpy (String Copy):
#include <string.h>
char destination[20];
strcpy(destination, greeting);
Copies the contents of one string to another.
strcat (String Concatenate):
#include <string.h>
strcat(destination, " World");
Concatenates (appends) one string to the end of another.
strcmp (String Compare):
#include <string.h>
int result = strcmp(greeting, "Hello");
Compares two strings lexicographically. Returns 0 if they are equal.
strchr (String Character):
#include <string.h>
char *position = strchr(greeting, 'l');
Finds the first occurrence of a character in a string.
strstr (String Substring):
#include <string.h>
char *substring = strstr(greeting, "llo");
Finds the first occurrence of a substring in a string.
Example:
This example demonstrates the basic usage of strings in C, including initialization, manipulation, and the use of common string functions. Strings in C are null-terminated character arrays, and understanding how to work with them is fundamental for C programmers.
0 Comments
If you have any doubts, Please let me know