Strings in C
Strings in C
Strings in C
In this tutorial, you'll learn about strings in C programming. You'll learn to declare them, initialize them and
use them for various I/O operations with the help of examples.
In C programming, a string is a sequence of characters terminated with a null character \0. For example:
1. char c[] = "c string";
When the compiler encounters a sequence of characters enclosed in the double quotation marks, it
appends a null character \0 at the end by default.
1. char s[5];
Output
Even though Dennis Ritchie was entered in the above program, only "Ritchie" was stored in
the name string. It's because there was a space after Dennis.
Here, we have used fgets() function to read a string from the user.
fgets(name, sizeof(name), stdlin); // read string
The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the size
of the name string.
To print the string, we have used puts(name);.
Note: The gets() function can also be to take input from the user. However, it is removed from the C
standard.
It's because gets() allows you to input any length of characters. Hence, there might be a buffer overflow.
String is an array of characters. In this guide, we learn how to declare strings, how to work with
strings in C programming and how to use the pre-defined string handling functions.
We will see how to compare two strings, concatenate strings, copy one string to another & perform
various string manipulation operations. We can perform such operations using the pre-defined
functions of “string.h” header file. In order to use these string functions you must include string.h
file in your C program.
String Declaration
Method 1:
char address[]="TEXAS";
In the above declaration NULL character (\0) will automatically be inserted at the end of the string.
/*Displaying String*/
printf("%s",nickname);
return 0;
}
Output:
puts(nickname);
return 0;
}
C – String functions
C String function – strlen
Syntax:
Example of strlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:
Example of strnlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
return 0;
}
Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10
Have you noticed the output of second printf statement, even though the string length was 13 it
returned only 10 because the maxlen was 10.
If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value.
If string1 > string2 then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for compare strings.
Example of strcmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
Example of strncmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
Example of strcat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
Example of strncat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:
Example of strcpy:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:
Example of strncpy:
#include <stdio.h>
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return 0;
}
Output:
f function strchr
C String function – Strrchr
char *strrchr(char *str, int ch)
It is similar to the function strchr, the only difference is that it searches the string in reverse order,
now you would have understood why we have extra r in strrchr, yes you guessed it correct, it is for
reverse only.
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strrchr(mystr, 'f'));
return 0;
}
Output:
function strchr
Why output is different than strchr? It is because it started searching from the end of the string
and found the first ‘f’ in function instead of ‘of’.
Example of strstr:
#include <stdio.h>
#include <string.h>
int main()
{
char inputstr[70] = "String Function in C at BeginnersBook.COM";
printf ("Output string is: %s", strstr(inputstr, 'Begi'));
return 0;
}
Output:
Output string is: BeginnersBook.COM
You can also use this function in place of strchr as you are allowed to give single char also in
place of search_term string.
C Library - <string.h>
The string.h header defines one variable type, one macro, and various functions for manipulating arrays
of characters.
Library Variables
Following is the variable type defined in the header string.h −
1
size_t
This is the unsigned integral type and is the result of the sizeof keyword.
Library Macros
Following is the macro defined in the header string.h −
1
NULL
This macro is the value of a null pointer constant.
Library Functions
Following are the functions defined in the header string.h −
Searches for the first occurrence of the character c (an unsigned char) in the first n bytes of the string
pointed to, by the argument str.
Searches an internal array for the error number errnum and returns a pointer to an error message
string.
16 size_t strlen(const char *str)
Computes the length of the string str up to but not including the terminating null character.
You need to often manipulate strings according to the need of a problem. Most, if not all, of the time string
manipulation can be done manually but, this makes programming complex and large.
To solve this, C supports a large number of string handling functions in the standard library "string.h".
#include <string.h>
Note: You have to include the code below to run string handling functions.
To understand this example, you should have the knowledge of following C programming topics:
C Programming Strings
String Manipulations In C Programming Using Library Functions
C for Loop
You can use standard library function strlen() to find the length of a string but, this program computes the
length of a string manually without using strlen() funtion.
To understand this example, you should have the knowledge of following C programming topics:
C Arrays
C Programming Strings
In this program, the string entered by the user is stored in variable str.
Then, the user is asked to enter the character whose frequency is to be found. This is stored in variable ch.
Now, using the for loop, each character in the string is checked for the entered character.
If, the character is found, the frequency is increased. If not, the loop continues.
To understand this example, you should have the knowledge of following C programming topics:
C Multidimensional Arrays
C Programming Strings
String Manipulations In C Programming Using Library Functions
This program takes 5 words (strings) from the user and sorts them in lexicographical order.
This string can hold a maximum of 5 strings and each string can have a maximum of 50 characters
(including the null character).
To compare two strings, the strcmp() function is used. And, we used the strcpy() function to copy string to
a temporary string, temp.
To understand this example, you should have the knowledge of following C programming topics:
C Arrays
C Programming Strings
C for Loop
C while and do...while Loop
This program takes a string from the user and stored in the variable line.
To understand this example, you should have the knowledge of following C programming topics:
C Arrays
C Programming Strings
C for Loop
You can use the strcpy() function to copy the content of one string to another but, this program copies the
content of one string to another manually without using strcpy() function.
To understand this example, you should have the knowledge of following C programming topics:
C Programming Operators
C if...else Statement
C while and do...while Loop
The five alphabets A, E, I, O and U are called vowels. All other alphabets except these 5 vowel letters are
called consonants.
This program assumes that the user will always enter an alphabet character.
The program above assumes that the user always enters an alphabet. If the user enters any other
character other than an alphabet, the program will not work as intended.
1. #include <stdio.h>
2. #include <ctype.h>
3.
4. int main()
5. {
6. char c;
7. int isLowercaseVowel, isUppercaseVowel;
8.
9. do {
10. printf("Enter an alphabet: ");
11. scanf(" %c", &c);
12. }
13. // isalpha() returns 0 if the passed character is not an alphabet
14. while (!isalpha(c));
15.
16. // evaluates to 1 (true) if c is a lowercase vowel
17. isLowercaseVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
18.
19. // evaluates to 1 (true) if c is an uppercase vowel
20. isUppercaseVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
21.
22. // evaluates to 1 (true) if either isLowercaseVowel or isUppercaseVowel is true
23. if (isLowercaseVowel || isUppercaseVowel)
24. printf("%c is a vowel.", c);
25. else
26. printf("%c is a consonant.", c);
27. return 0;
28. }
C Program to Count the Number of Vowels,
Consonants and so on
This program counts the number of vowels, consonants, digits and white-spaces in a string which is
entered by the user.
To understand this example, you should have the knowledge of following C programming topics:
C Arrays
C Programming Strings
This program takes string input from the user and stores in variable line.
Initially, the variables vowels, consonants, digits and spaces are initialized to 0.
When the vowel character is found, vowel variable is incremented by 1.
Similarly, consonants, digits and spaces are incremented when these characters are found.
C strcmp()
The strcmp() function compares two strings and returns 0 if both strings are identical.
C strcmp() Prototype
int strcmp (const char* str1, const char* str2);
negative if the ASCII value of the first unmatched character is less than second.
positive integer if the ASCII value of the first unmatched character is greater than second.
Example: C strcmp() function
1. #include <stdio.h>
2. #include <string.h>
3.
4. int main()
5. {
6. char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
7. int result;
8.
9. // comparing strings str1 and str2
10. result = strcmp(str1, str2);
11. printf("strcmp(str1, str2) = %d\n", result);
12.
13. // comparing strings str1 and str3
14. result = strcmp(str1, str3);
15. printf("strcmp(str1, str3) = %d\n", result);
16.
17. return 0;
18. }
Output
strcmp(str1, str2) = 32
strcmp(str1, str3) = 0
The first unmatched character between string str1 and str2 is third character. The ASCII value of 'c' is 99
and the ASCII value of 'C' is 67. Hence, when strings str1 and str2 are compared, the return value is 32.
When strings str1 and str3 are compared, the result is 0 because both strings are identical.
To understand this example, you should have the knowledge of following C programming topics:
C if...else Statement
C while and do...while Loop
In this program, the for loop is used to display the English alphabets in uppercase.
Here's a little modification of the above program. The program displays the English alphabets in either
uppercase or lowercase depending upon the input from the user.
To understand this example, you should have the knowledge of following C programming topics:
C Arrays
C Programming Strings
C for Loop
C while and do...while Loop
This program takes a string from the user and stored in the variable line.
The, within the for loop, each character in the string is checked if it's an alphabet or not.
If any character inside a string is not a alphabet, all characters after it including the null character is shifted
by 1 position to the left.
C program to Reverse a Sentence Using Recursion
This program takes a sentence from user and reverses that sentence using recursion. This program does
not use string to reverse the sentence or store the sentence.
To understand this example, you should have the knowledge of following C programming topics:
C Functions
C User-defined functions
C Recursion
This program first prints "Enter a sentence: ". Then, immediately reverseSentence() function is called.
This function stores the first letter entered by user in variable c. If the variable is any character other than
'\n' [ enter character], reverseSentence() function is called again.
When reverseSentence() is called the second time, the second letter entered by the user is stored
in c again.
But, the variable c in the second function isn't the same as the first. They both take different space in the
memory.
When, the user finally enters '\n', the last function reverseSentence() function prints the last character
because of printf("%c", c); and returns to the second last reverseSentence() function.
Again, the second last reverseSentence() function prints the second last character and returns to the third
last reverseSentence() function.
This process goes on and the final output will be the reversed sentence.