Home »
C programming language
Strings in C Programming Language (With Examples)
Strings in C programming language: In this tutorial, we will learn about the strings in C, declaring, initializing, printing getting the length of the string, and many more with the help of examples.
By Sneha Dujaniya Last updated : December 26, 2023
What are Strings?
Strings are mostly considered difficult by many beginners but trust me, Strings are no big deal. A string is nothing but a group of characters stored in a character array. Character arrays are used in programming languages to manipulate words and sentences.
A string is a constant in the form of the one-dimensional array of characters terminated by a null character which is \0. Example,
char city[] = {'T', 'O', 'K', 'Y', 'O', '\0'};
Points to be noted:
- Memory space occupied by each character is one byte and the last character has to be null \0.
- \0 should not be confused with the digit 0 since the ASCII value of null is 0 whereas that of ‘0' is 48.
- The members of the array are stored in contiguous memory locations as shown below.
- The null character at the end is very important because that is the only way for the compiler to know where the string ends. But to be noted, the null declaration is not necessary. It is inserted by the compiler automatically as in the following example: char city[] = "TOKYO";
- The format specification used for printing and receiving a string is "%s".
Declaring String
The string is a character array. Thus, to declare a string, you need to create a character array with the maximum size of the string.
Syntax
char string_name[maximum_size];
Example
Declare a string to store a name.
char name[30];
Initialize String
There are multiple methods to initialize string.
1. Initialize string during declaration
You can initialize a string during declaration in the following ways:
char name1[30] = "Alvin Alexander";
char name2[] = "Alvin Alexander";
char name3[30] = {'A','l','v','i','n',' ','A','l','e','x','a','n','d','e','r'};
char name4[30] = {'A','l','v','i','n',' ','A','l','e','x','a','n','d','e','r'};
2. Initialize string by using strcpy() or memcpy()
You cannot directly assign a string by using the assignment (=) operator. You can initialize a string anywhere in the program after the declaration by using either strcpy() or memcpy() function.
strcpy(name, "Alvin Alexander");
memcpy(name, "Alvin Alexander", 15);
Printing String
To print a string in language, you can use printf() and puts() functions. The printf() function requires "%s" format specifier to display the string value whereas the puts() function just takes the string variable as an argument.
Example
#include <stdio.h>
int main() {
// Declaring string
char name[] = "Alvin Alexander";
// Printing string using printf()
printf("The name is : %s\n", name);
// Using puts()
puts(name);
return 0;
}
Output
The name is : Alvin Alexander
Alvin Alexander
Printing String Variable Size
To print the occupied memory size (in bytes) by a string variable, you can use the sizeof() operator.
Example
#include <stdio.h>
int main() {
// Declaring string
char name[30] = "Alvin Alexander";
// Printing string using printf()
printf("The name is : %s\n", name);
// Printing size of the variable
printf("Variable name took %ld bytes in memory.", sizeof(name));
return 0;
}
Output
The name is : Alvin Alexander
Variable name took 30 bytes in memory.
Getting String Length
There are two ways to get the string length: Using the strlen() method (which is a library function of string.h header), and by counting each character of the string using the loop (for that you can create a function to get the string length).
Example
#include <stdio.h>
#include <string.h>
// Function to get the length of string
int StringLength(const char str[])
{
int i = 0, len = 0;
while (str[i++] != '\0')
len++;
return len;
}
int main()
{
// Declaring string
char name[30] = "Alvin Alexander";
// Printing string using printf()
printf("The name is : %s\n", name);
// Length of string using library function strlen()
printf("The lenght is : %ld\n", strlen(name));
// Length of string using our function StringLength()
printf("The lenght is : %d\n", StringLength(name));
return 0;
}
Output
The name is : Alvin Alexander
The lenght is : 15
The lenght is : 15
C Strings: More Examples
Now let us see some of the examples:
Example 1: Declare string and print character by character
#include <stdio.h>
int main() {
//declaring string
char city[] = "Tokyo";
//loop counter
int i = 0;
//printing string one by one character
while (i <= 4) {
printf("%c", city[i]);
i++;
}
return 0;
}
Output
Tokyo
Simple program, where we are treating the string as a character array and we use %c in printf() statement. Also, the length of the word is taken to be 4 because the value of the first element in an array is always assigned 0, as we all know already. But this solution is not profitable if we have a bigger string.
So, here is another way to do it:
Example 2: Declare string and print character by character till NULL not found
#include <stdio.h>
int main() {
//declaring string
char city[] = "Tokyo";
//loop counter
int i = 0;
//printing string one by one character
//till NULL ('\0') not found
while (city[i] != '\0') {
printf("%c", city[i]);
i++;
}
return 0;
}
Output
Tokyo
Example 3: Declaring string and printing as string (using "%s" format specifier)
#include <stdio.h>
int main() {
//declaring string
char city[] = "Tokyo";
//print as string
//using "%s" format specifier
printf("%s", city);
return 0;
}
Output
Tokyo
This was the simplest way to print a string using the general specification of %s.
Example 4: Reading string using scanf() function
#include <stdio.h>
int main() {
//declaring string/character array
char city[15];
//read string
printf("Enter a city: ");
scanf("%s", city);
//printing string
printf("Good Morning %s!", city);
return 0;
}
Output
Enter a city: Mumbai
Good Morning Mumbai!
Here, the declaration char city[15] stores 15 bytes of memory under the array city[]. Whereas, the scanf() function fills the characters entered till the enter key is pressed by the user. After that, scanf() automatically adds a null character leaving the further memory blank.
Reading a string using scanf() or gets()?
Points to be kept in mind while using scanf():
- The length of the string entered by the user should not exceed the value declared in the array since C compilers do not show any Array index out of bound error for this. It will simply result in the overwriting of important data.
- Using scanf(), we can't enter a multi-word string, for example, "New York". This problem can be resolved by using the function gets() and puts() as shown below,
Use of gets() and puts()
#include <stdio.h>
int main() {
//declaring string/character array
char city[15];
//read the string
printf("Enter a city: ");
gets(city);
//printing the string
puts("Good Morning!");
puts(city);
return 0;
}
Output
Enter a city: New York
Good Morning!
New York
Here, puts() can display only one string at a time therefore, two puts() statements are used. Also, unlike printf(), it places the cursor automatically to the next line.
Though gets() can receive only one string at a time, still it is preferable as it can receive multi-word strings.
Author's note:
This was a basic of what strings actually are. In the next article, I will write about string manipulations and standard library string functions. For better understanding, practice these codes on your own by changing the values and outputs. I'm ready to help if the case of queries. Happy coding!