Strings are defined as a one-dimensional array of characters. They are terminated by a null character ‘\0’. Thie above is the difference between arrays and strings. It is also referred to as a character array.
Declaration of strings:
It is similar to declaring 1-D arrays.
Syntax:
char str_name[size];
Initializing a String:
It can be done in several ways, similar to arrays,
1. char str[] = "HelloWorld"; 2. char str[50] = "HelloWorld"; 3. char str[] = {'H','e','l','l','o','W','o','r','l','d','\0'}; 4. char str[11] = {'H','e','l','l','o','W','o','r','l','d','\0'};
Memory Representation of a string:

Example Program:
#include <stdio.h> int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message: %s\n", greeting ); return 0; }
Output:
Greeting message: Hello
The null character is not printed at the end of a string constant. When it initializes the array, the C compiler automatically places the ‘\0’ at the end of the string.
Manipulating Strings:
Sr.No. | Function & Purpose |
---|---|
1. | strcpy(s1, s2); Copies string s2 into string s1. |
2. | strcat(s1, s2); Concatenates string s2 onto the end of string s1. |
3. | strlen(s1); Returns the length of string s1. |
Example Program: Using the above functions
#include <stdio.h> #include <string.h> int main () { char string_1[12] = "Hello"; char string_2[12] = "World"; char string_3[12]; int len ; strcpy(string_3, string_1); /* copy str1 into str3 */ printf("The copied string is : %s\n", string_3 ); strcat( string_1, string_2); /* concatenates str1 and str2 */ printf("The concatenated string is : %s\n", string_1 ); len = strlen(string_1); /* total lenghth of str1 after concatenation */ printf("Length of concatenated string is : %d\n", len ); return 0; }
Output:
The copied string is : Hello The concatenated string is : HelloWorld Length of concatenated string is : 10