C Strings
A string in C is a sequence of characters terminated by a null character (\0). The null character is a special character that has the ASCII value 0. Strings are stored in memory as arrays of characters, but they are treated differently than other arrays.
C String
To declare a string in C, you use the char keyword followed by the name of the string variable and the size of the array. For example, the following code declares a string variable called name that can hold up to 50 characters:
You can also initialize a string variable when you declare it. To do this, you enclose the string literal in double quotes. For example, the following code declares a string variable called greeting and initializes it to the string "Hello, world!"
To access the characters in a string, you use the square bracket operator ([]). For example, the following code prints the first character of the name string variable:
You can also use the strlen() function to get the length of a string. The strlen() function returns the number of characters in a string, excluding the null terminator. For example, the following code prints the length of the greeting string variable:
The following code shows a complete example of how to use strings in C:
Full Source | C StringString functions in C
There are a number of built-in string functions in C. These functions can be used to perform various operations on strings, such as copying, concatenating, and comparing strings.
Here are some examples of built-in string functions in C:
- strcpy(): Copies one string to another string.
- strcat(): Concatenates two strings.
- strcmp(): Compares two strings.
- strstr(): Finds the first occurrence of one substring in another string.
- strtok(): Breaks a string into tokens.
Conclusion
Strings are typically represented as null-terminated character arrays, with each character followed by a null character ('\0') to mark the string's end. String manipulation is facilitated through standard library functions like strlen, strcpy, and strcat, enabling tasks such as string length determination, copying, concatenation, and comparison. These functions, combined with character arrays, allow C programmers to work with text-based data efficiently.