C Strings
Strings
Strings are used for storing text/characters.
For example, "Hello World" is a string of characters.
Unlike many other programming languages, C does not have a String type
to easily create string variables. Instead, you must use the char type and create
an array of characters to make a string in C:
char greetings[] = "Hello World!";
Note that you have to use double quotes ("").
To output the string, you can use the printf() function together with the format specifier %s to tell C that we are now working with strings:
Access Strings
Since strings are actually arrays in C, you can access a string by referring to its index number inside square brackets [].
This example prints the first character (0) in greetings:
Note that we have to use the %c format specifier to print a
single character.
Modify Strings
To change the value of a specific character in a string, refer to the index number, and use single quotes:
Example
char greetings[] = "Hello World!";
greetings[0] = 'J';
printf("%s", greetings);
// Outputs Jello World! instead of Hello
World!
Try it Yourself »
Real-Life Example
Use strings to create a simple welcome message:
Example
char message[] = "Good to see you,";
char fname[] = "John";
printf("%s
%s!", message, fname);
Try it Yourself »