UNIT-3
Strings in C
A string in C is a one-dimensional array of char type, with the last character in the array
being a "null character" represented by '\0'. Thus, a string in C can be defined as a null-
terminated sequence of char type values.
Creating a String in C
Let us create a string "Hello". It comprises five char values. In C, the literal representation of
a char type uses single quote symbols − such as 'H'. These five alphabets put inside single
quotes, followed by a null character represented by '\0' are assigned to an array of char types.
The size of the array is five characters plus the null character − six.
Example
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Initializing String Without Specifying Size
C lets you initialize an array without declaring the size, in which case the compiler
automatically determines the array size.
Example
char greeting[] = {'H', 'e', 'l', 'l', 'o', '\0'};
The array created in the memory can be schematically shown as follows −
If the string is not terminated by "\0", it results in unpredictable behavior.
Note: The length of the string doesn’t include the null character. The library
function strlen() returns the length of this string as 5.
Loop Through a String
You can loop through a string (character array) to access and manipulate each character of
the string using the for loop or any other loop statements.
Example
In the following example, we are printing the characters of the string.
Open Compiler
#include <stdio.h>
#include <string.h>
int main (){
char greeting[] = {'H', 'e', 'l', 'l', 'o', '\0'};
for (int i = 0; i < 5; i++) {
printf("%c", greeting[i]);
}
return 0;
}
Output
It will produce the following output −
Hello
Printing a String (Using %s Format Specifier)
C provides a format specifier "%s" which is used to print a string when you're using
functions like printf() or fprintf() functions.
Example
The "%s" specifier tells the function to iterate through the array, until it encounters the null
terminator (\0) and printing each character. This effectively prints the entire string
represented by the character array without having to use a loop.
Open Compiler
#include <stdio.h>
int main (){
char greeting[] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
Output
It will produce the following output −
Greeting message: Hello
You can declare an oversized array and assign less number of characters, to which the C
compiler has no issues. However, if the size is less than the characters in the initialization,
you may get garbage values in the output.
char greeting[3] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("%s", greeting);
Constructing a String using Double Quotes
Instead of constructing a char array of individual char values in single quotation marks, and
using "\0" as the last element, C lets you construct a string by enclosing the characters within
double quotation marks. This method of initializing a string is more convenient, as the
compiler automatically adds "\0" as the last character.
Example
Open Compiler
#include <stdio.h>
int main() {
// Creating string
char greeting[] = "Hello World";
// Printing string
printf("%s\n", greeting);
return 0;
}
Output
It will produce the following output −
Hello World
String Input Using scanf()
Declaring a null-terminated string causes difficulty if you want to ask the user to input a
string. You can accept one character at a time to store in each subscript of an array, with the
help of a for loop −
Syntax
for(i = 0; i < 6; i++){
scanf("%c", &greeting[i]);
}
greeting[i] = '\0';
Example
In the following example, you can input a string using scanf() function, after inputting the
specific characters (5 in the following example), we are assigning null ('\0') to terminate the
string.
printf("Starting typing... ");
for (i = 0; i < 5; i++) {
scanf("%c", &greeting[i]);
}
// Assign NULL manually
greeting[i] = '\0';
// Printing the string
printf("Value of greeting: %s\n", greeting);
Output
Run the code and check its output −
Starting typing... Hello
Value of greeting: Hello
Example
It is not possible to input "\0" (the null string) because it is a non-printable character. To
overcome this, the "%s" format specifier is used in the scanf() statement −
Open Compiler
#include <stdio.h>
#include <string.h>
int main (){
char greeting[10];
printf("Enter a string:\n");
scanf("%s", greeting);
printf("You entered: \n");
printf("%s", greeting);
return 0;
}
Output
Run the code and check its output −
Enter a string:
Hello
You entered:
Hello
Note: If the size of the array is less than the length of the input string, then it may result in
situations such as garbage, data corruption, etc.
String Input with Whitespace
scanf("%s") reads characters until it encounters a whitespace (space, tab, newline, etc.) or
EOF. So, if you try to input a string with multiple words (separated by whitespaces), then the
C program would accept characters before the first whitespace as the input to the string.
Example
Take a look at the following example −
Open Compiler
#include <stdio.h>
#include <string.h>
int main (){
char greeting[20];
printf("Enter a string:\n");
scanf("%s", greeting);
printf("You entered: \n");
printf("%s", greeting);
return 0;
}
Output
Run the code and check its output −
Enter a string:
Hello World!
You entered:
Hello
String Input Using gets() and fgets() Functions
To accept a string input with whitespaces in between, we should use the gets() function. It is
called an unformatted console input function, defined in the "stdio.h" header file.
Example: String Input Using gets() Function
Take a look at the following example −
Open Compiler
#include <stdio.h>
#include <string.h>
int main(){
char name[20];
printf("Enter a name:\n");
gets(name);
printf("You entered: \n");
printf("%s", name);
return 0;
}
Output
Run the code and check its output −
Enter a name:
Sachin Tendulkar
You entered:
Sachin Tendulkar
In newer versions of C, gets() has been deprecated. It is potentially a dangerous function
because it doesn’t perform bound checks and may result in buffer overflow.
Instead, it is advised to use the fgets() function.
fgets(char arr[], size, stream);
The fgets() function can be used to accept input from any input stream, such as stdin
(keyboard) or FILE (file stream).
Example: String Input Using fgets() Function
The following program uses fgets() and accepts multiword input from the user.
Open Compiler
#include <stdio.h>
#include <string.h>
int main(){
char name[20];
printf("Enter a name:\n");
fgets(name, sizeof(name), stdin);
printf("You entered: \n");
printf("%s", name);
return 0;
}
Output
Run the code and check its output −
Enter a name:
Virat Kohli
You entered:
Virat Kohli
Example: String Input Using scanf("%[^\n]s")
You may also use scanf("%[^\n]s") as an alternative. It reads the characters until a newline
character ("\n") is encountered.
Open Compiler
#include <stdio.h>
#include <string.h>
int main (){
char name[20];
printf("Enter a name: \n");
scanf("%[^\n]s", name);
printf("You entered \n");
printf("%s", name);
return 0;
}
Output
Run the code and check its output −
Enter a name:
Zaheer Khan
You entered
Zaheer Khan
Printing String Using puts() and fputs() Functions
We have been using printf() function with %s specifier to print a string. We can also
use puts() function (deprecated in C11 and C17 versions) or fputs() function as an alternative.
Example
Take a look at the following example −
Open Compiler
#include <stdio.h>
#include <string.h>
int main (){
char name[20] = "Rakesh Sharma";
printf("With puts(): \n");
puts(name);
printf("With fputs(): \n");
fputs(name, stdout);
return 0;
}
Output
Run the code and check its output −
With puts():
Harbhajan Singh
With fputs():
Harbhajan Singh
Operations of String
String Length
Length of a string is all the characters in it and one count more for the string termination
symbol \0.
#include <stdio.h>
int main()
{
char s1[] = "TajMahal";
int i = 0;
while(s1[i] != '\0')
{
i++;
}
printf("Length of string '%s' is %d", s1, i);
return 0;
}
The output should be −
Length of string 'TajMahal' is 8
Count Vowels in a string
This example also uses the concept of searching, iteration and counting. We shall search
entire string using iteration and increase the count whenever a vowel is found. If the character
is not vowel, then it will be a consonant for sure, hence we increment consonant in this case.
String copy
We now should learn how to copy value of one string variable to other. This example is easy
as we already know how to traverse a string character by character. The additional task we
shall do here, is to while traversing the string we shall copy that character to some other
string variable. Let's see this example −
#include <stdio.h>
int main()
{
char s1[] = "TajMahal"; // String Given
char s2[8]; // Variable to hold value
int length = 0;
while(s1[length] != '\0')
{
s2[length] = s1[length];
length++;
}
s2[length] = '\0'; // Terminate the string
printf("Value in s1 = %s \n", s1);
printf("Value in s2 = %s \n", s2);
return 0;
}
Reverse a string
This example can be solved in two ways, one is to print the string in reverse and second one
is store the reversed string in some another string and then print it. We shall try to solve it
both ways −
#include <stdio.h>
int main()
{
char s1[] = "TajMahal"; // String Given
char s2[8]; // Variable to store reverse string
int length = 0;
int loop = 0;
while(s1[length] != '\0')
{
length++;
}
printf("\nPrinting in reverse - ");
for(loop = --length; loop>=0; loop--)
printf("%c", s1[loop]);
loop = 0;
printf("\nStoring in reverse - ");
while(length >= 0)
{
s2[length] = s1[loop];
length--;
loop++;
}
s1[loop] = '\0'; // Terminates the string
printf("%s\n", s2);
return 0;
}
The output should be −
Printing in reverse - lahaMjaT
Storing in reverse - lahaMjaT
Terminating the string with \0 is a good practice as in case of string pointers, it can lead to
unwanted errors.
Swapping Strings
Swapping of strings values between two variables can be done in several ways. It can be done
via pointers, character by character copying of strings, using inbuilt functions like strcpy etc.
We shall do in a simple way.
#include <stdio.h>
int main()
{
char s1[] = "TajMahal";
char s2[] = "Dazzling";
char ch;
int index = 0;
//Character by Character approach
printf("Before Swapping - \n");
printf("Value of s1 - %s \n", s1);
printf("Value of s2 - %s \n", s2);
while(s1[index] != '\0')
{
ch = s1[index];
s1[index] = s2[index];
s2[index] = ch;
index++;
}
printf("After Swapping - \n");
printf("Value of s1 - %s \n", s1);
printf("Value of s2 - %s \n", s2);
return 0;
}
Output should be −
Before Swapping -
Value of s1 - TajMahal
Value of s2 - Dazzling
After Swapping -
Value of s1 - Dazzling
Value of s2 - TajMahal
What should happen if you try to resize a string variable? What if the strings are not of same
size? Well, in that case we need to use pointers. If we dynamically try to change size of an
character array, it will produce Segmentation fault. We shall learn that too, but later!
String Compare
Comparing two string requires to traverse both string simultaneously and compare each
character. If at any point of traversal we encounter non-matching character, we declare that
strings are not identical. Let's learn this with example −
#include <stdio.h>
int main()
{
char s1[] = "advise";
char s2[] = "advice";
int n = 0;
unsigned short flag = 1;
while (s1[n] != '\0')
{
if(s1[n] != s2[n])
{
flag = 0;
break;
}
n++;
}
if(flag == 1)
{
printf("%s and %s are identical\n", s1, s2);
}
else
{
printf("%s and %s are NOT identical\n", s1, s2);
}
return 0;
}
The output should be −
advise and advice are NOT identical
String Concatenation
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Taj";
char s2[] = "Mahal";
int i, j, n1, n2;
n1 = strlen(s1);
n2 = strlen(s2);
j=0;
for(i = n1; i<n1+n2; i++ )
{
s1[i] = s2[j];
j++;
}
s1[i] = '\0';
printf("%s", s1);
return 0;
}
Output of the program should be −
TajMahal
String Searching
Searching a string in a sentence involves a bit complex algorithm. The basic thing to learn
that we should get a match exactly of the size of search string.
#include <stdio.h>
#include <string.h>
int main()
{
char s1[] = "Beauty is in the eye of the beholder";
char s2[] = "the";
int n = 0;
int m = 0;
int times = 0;
int len = strlen(s2); // contains the length of search string
while(s1[n] != '\0')
{
if(s1[n] == s2[m]) // if first character of search string matches
{
// keep on searching
while(s1[n] == s2[m] && s1[n] !='\0')
{
n++;
m++;
}
// if we sequence of characters matching with the length of searched string
if(m == len && (s1[n] == ' ' || s1[n] == '\0'))
{
// BINGO!! we find our search string.
times++;
}
}
else // if first character of search string DOES NOT match
{
while(s1[n] != ' ') // Skip to next word
{
n++;
if(s1[n] == '\0')
break;
}
}
n++;
m=0; // reset the counter to start from first character of the search string.
}
if(times > 0)
{
printf("'%s' appears %d time(s)\n", s2, times);
}
else
{
printf("'%s' does not appear in the sentence.\n", s2);
}
return 0;
}
The output of this program should be −
'the' appears 2 time(s)
Sorting Characters in String
We know that all (printable) characters have their own unique ASCII values. So it becomes
easier to sort characters in a string by comparing their ASCII values. We should know that
ASCII value of 'a' (97) and 'A' (65) are different, therefore, if a string contains both capital
and small letters then capital letters will appear first after sorting.
#include <stdio.h>
#include <string.h>
int main (void)
{
char string[] = "simplyeasylearning";
char temp;
int i, j;
int n = strlen(string);
printf("String before sorting - %s \n", string);
for (i = 0; i < n-1; i++)
{
for (j = i+1; j < n; j++)
{
if (string[i] > string[j])
{
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}
}
printf("String after sorting - %s \n", string);
return 0;
}
The output should be −
String before sorting - simplyeasylearning
String after sorting - aaeegiillmnnprssyy
Write a program to reverse a string.
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int start = 0;
int end = strlen(str) - 1;
char temp;
// Swap characters from both ends
while (start < end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char str[40]; // declare the size of the character string
printf("Enter a string to be reversed: ");
scanf("%s", str);
// Reverse the string
reverseString(str);
// Print the reversed string
printf("After reversing the string: %s\n", str);
return 0;
}
Example Walkthrough
Let’s assume str = "hello".
1. Initial values:
o start = 0 (first character: 'h')
o end = 4 (last character: 'o')
2. First iteration:
o temp = str[0] = 'h'
o str[0] = str[4] = 'o' (Now str = "oello")
o str[4] = temp = 'h' (Now str = "oellh")
o start++ → start = 1
o end-- → end = 3
3. Second iteration:
o temp = str[1] = 'e'
o str[1] = str[3] = 'l' (Now str = "olleh")
o str[3] = temp = 'e' (Now str = "olleh")
o start++ → start = 2
o end-- → end = 2
4. Final check:
o Now, start = 2 and end = 2. The condition start < end is false, so the
loop stops. The string is fully reversed as "olleh".