Strings in C

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

C Programming Strings

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.

How to declare a string?


Here's how you can declare strings:

1. char s[5];

Here, we have declared a string of 5 characters.

How to initialize strings?


You can initialize strings in a number of ways.

1. char c[] = "abcd";


2.
3. char c[50] = "abcd";
4.
5. char c[] = {'a', 'b', 'c', 'd', '\0'};
6.
7. char c[5] = {'a', 'b', 'c', 'd', '\0'};

Let's take another example:


1. char c[5] = "abcde";
Here, we are trying to assign 6 characters (the last character is '\0') to a char array having 5 characters.
This is bad and you should never do this.

Read String from the user


You can use the scanf() function to read a string.
The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab
etc.).

Example 1: scanf() to read a string


1. #include <stdio.h>
2. int main()
3. {
4. char name[20];
5. printf("Enter name: ");
6. scanf("%s", name);
7. printf("Your name is %s.", name);
8. return 0;
9. }

Output

Enter name: Dennis Ritchie


Your name is Dennis.

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.

How to read a line of text?


You can use the fgets() function to read a line of string. And, you can use puts() to display the string.

Example 2: fgets() and puts()


1. #include <stdio.h>
2. int main()
3. {
4. char name[30];
5. printf("Enter name: ");
6. fgets(name, sizeof(name), stdin); // read string
7. printf("Name: ");
8. puts(name); // display string
9. return 0;
10. }
Output
Enter name: Tom Hanks
Name: Tom Hanks

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.

Passing Strings to Functions


Strings can be passed to a function in a similar way as arrays. Learn more about passing arrays to a
function.

Example 3: Passing string to a Function


1. #include <stdio.h>
2. void displayString(char str[]);
3.
4. int main()
5. {
6. char str[50];
7. printf("Enter string: ");
8. fgets(str, sizeof(str), stdin);
9. displayString(str); // Passing string to a function.
10. return 0;
11. }
12. void displayString(char str[])
13. {
14. printf("String Output: ");
15. puts(str);
16. }

Strings and Pointers


Similar like arrays, string names are "decayed" to pointers. Hence, you can use pointers to manipulate
elements of the string. We recommended you to check C Arrays and Pointers before you check this
example.

Example 4: Strings and Pointers


1. #include <stdio.h>
2.
3. int main(void) {
4. char name[] = "Harry Potter";
5.
6. printf("%c", *name); // Output: H
7. printf("%c", *(name+1)); // Output: a
8. printf("%c", *(name+7)); // Output: o
9.
10. char *namePtr;
11.
12. namePtr = name;
13. printf("%c", *namePtr); // Output: H
14. printf("%c", *(namePtr+1)); // Output: a
15. printf("%c", *(namePtr+7)); // Output: o
16. }

Commonly Used String Functions


 strlen() - calculates the length of a string
 strcpy() - copies a string to another
 strcmp() - compares two strings
 strcat() - concatenates two strings

C – Strings and String functions with examples


BY CHAITANYA SINGH | FILED UNDER: C-PROGRAMMING

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[]={'T', 'E', 'X', 'A', 'S', '\0'};


Method 2: The above string can also be defined as –

char address[]="TEXAS";
In the above declaration NULL character (\0) will automatically be inserted at the end of the string.

What is NULL Char “\0”?


'\0' represents the end of the string. It is also referred as String terminator & Null Character.
String I/O in C programming

Read & write Strings in C using Printf() and Scanf() functions


#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

printf("Enter your Nick name:");

/* I am reading the input string and storing it in nickname


* Array name alone works as a base address of array so
* we can use nickname instead of &nickname here
*/
scanf("%s", nickname);

/*Displaying String*/
printf("%s",nickname);

return 0;
}
Output:

Enter your Nick name:Negan


Negan
Note: %s format specifier is used for strings input/output

Read & Write Strings in C using gets() and puts() functions


#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

/* Console display using puts */


puts("Enter your Nick name:");

/*Input using gets*/


gets(nickname);

puts(nickname);

return 0;
}
C – String functions
C String function – strlen
Syntax:

size_t strlen(const char *str)


size_t represents unsigned short
It returns the length of the string without including end character (terminating char ‘\0’).

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:

Length of string str1: 13


strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof returns the total allocated
size assigned to the array. So if I consider the above example again then the following statements
would return the below values.

strlen(str1) returned value 13.


sizeof(str1) would return value 20 as the array size is 20 (see the first statement in main function).

C String function – strnlen


Syntax:

size_t strnlen(const char *str, size_t maxlen)


size_t represents unsigned short
It returns length of the string if it is less than the value specified for maxlen (maximum length)
otherwise it returns maxlen value.

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.

C String function – strcmp


int strcmp(const char *str1, const char *str2)
It compares the two strings and returns an integer value. If both the strings are same (equal) then
this function would return 0 otherwise it may return a negative or positive value based on the
comparison.

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:

string 1 and 2 are different


C String function – strncmp
int strncmp(const char *str1, const char *str2, size_t n)
size_t is for unassigned short
It compares both the string till n characters or in other words it compares first n characters of both
the strings.

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:

string1 and string 2 are equal


C String function – strcat
char *strcat(char *str1, char *str2)
It concatenates two strings and returns the concatenated string.

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:

Output string after concatenation: HelloWorld


C String function – strncat
char *strncat(char *str1, char *str2, int n)
It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will always be appended
at the end of the concatenated string.

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:

Concatenation using strncat: HelloWor


C String function – strcpy
char *strcpy( char *str1, char *str2)
It copies the string str2 into string str1, including the end character (terminator char ‘\0’).

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:

String s1 is: string 2: I’m gonna copied into s1


C String function – strncpy
char *strncpy( char *str1, char *str2, size_t n)
size_t is unassigned short and n is a number.
Case1: If length of str2 > n then it just copies first n characters of str2 into str1.
Case2: If length of str2 < n then it copies all the characters of str2 into str1 and appends several
terminator chars(‘\0’) to accumulate the length of str1 to make it n.

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:

String s1 is: string 2: I’m


C String function – strchr
char *strchr(char *str, int ch)
It searches string str for character ch (you may be wondering that in above definition I have given
data type of ch as int, don’t worry I didn’t make any mistake it should be int only. The thing is when
we give any character while using strchr then it internally gets converted into integer for better
searching.
Example of strchr:

#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.

Now let’s take the same above example:

#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’.

C String function – strstr


char *strstr(char *str, char *srch_term)
It is similar to strchr, except that it searches for string srch_term instead of a single char.

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 −

Sr.No. Variable & Description

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 −

Sr.No. Macro & Description

1
NULL
This macro is the value of a null pointer constant.

Library Functions
Following are the functions defined in the header string.h −

Sr.No. Function & Description

1 void *memchr(const void *str, int c, size_t n)

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.

2 int memcmp(const void *str1, const void *str2, size_t n)


Compares the first n bytes of str1 and str2.
3 void *memcpy(void *dest, const void *src, size_t n)
Copies n characters from src to dest.

4 void *memmove(void *dest, const void *src, size_t n)


Another function to copy n characters from str2 to str1.

5 void *memset(void *str, int c, size_t n)


Copies the character c (an unsigned char) to the first n characters of the string pointed to, by the
argument str.

6 char *strcat(char *dest, const char *src)


Appends the string pointed to, by src to the end of the string pointed to by dest.

7 char *strncat(char *dest, const char *src, size_t n)


Appends the string pointed to, by src to the end of the string pointed to, by dest up to n characters long.

8 char *strchr(const char *str, int c)


Searches for the first occurrence of the character c (an unsigned char) in the string pointed to, by the
argument str.

9 int strcmp(const char *str1, const char *str2)


Compares the string pointed to, by str1 to the string pointed to by str2.

10 int strncmp(const char *str1, const char *str2, size_t n)


Compares at most the first n bytes of str1 and str2.

11 int strcoll(const char *str1, const char *str2)


Compares string str1 to str2. The result is dependent on the LC_COLLATE setting of the location.

12 char *strcpy(char *dest, const char *src)


Copies the string pointed to, by src to dest.

13 char *strncpy(char *dest, const char *src, size_t n)


Copies up to n characters from the string pointed to, by src to dest.

14 size_t strcspn(const char *str1, const char *str2)


Calculates the length of the initial segment of str1 which consists entirely of characters not in str2.

15 char *strerror(int errnum)

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.

17 char *strpbrk(const char *str1, const char *str2)


Finds the first character in the string str1 that matches any character specified in str2.

18 char *strrchr(const char *str, int c)


Searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the
argument str.

19 size_t strspn(const char *str1, const char *str2)


Calculates the length of the initial segment of str1 which consists entirely of characters in str2.

20 char *strstr(const char *haystack, const char *needle)


Finds the first occurrence of the entire string needle (not including the terminating null character) which
appears in the string haystack.

21 char *strtok(char *str, const char *delim)


Breaks string str into a series of tokens separated by delim.

22 size_t strxfrm(char *dest, const char *src, size_t n)


Transforms the first n characters of the string src into current locale and places them in the string dest.

String Manipulations In C Programming Using Library


Functions
In this article, you'll learn to manipulate strings in C using library functions such as gets(), puts, strlen() and
more. You'll learn to get string from the user and perform operations on the string.

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".

Few commonly used string handling functions are discussed below:


Function Work of Function

strlen() computes string's length

strcpy() copies a string to another

strcat() concatenates(joins) two strings

strcmp() compares two strings

strlwr() converts string to lowercase

strupr() converts string to uppercase

Strings handling functions are defined under "string.h" header file.

#include <string.h>

Note: You have to include the code below to run string handling functions.

gets() and puts()


Functions gets() and puts() are two string functions to take string input from the user and display it
respectively as mentioned in the previous chapter.
1. #include<stdio.h>
2.
3. int main()
4. {
5. char name[30];
6. printf("Enter name: ");
7. gets(name); //Function to read string from user.
8. printf("Name: ");
9. puts(name); //Function to display string.
10. return 0;
11. }
Note: Though, gets() and puts() function handle strings, both these functions are defined
in "stdio.h" header file.

C Program to Find the Length of a String


In this article, you'll learn to find the length of a string without using strlen() function.

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.

Example: Calculate Length of String without Using strlen() Function


1. #include <stdio.h>
2. int main()
3. {
4. char s[1000];
5. int i;
6.
7. printf("Enter a string: ");
8. scanf("%s", s);
9.
10. for(i = 0; s[i] != '\0'; ++i);
11.
12. printf("Length of string: %d", i);
13. return 0;
14. }
Output
Enter a string: Programiz
Length of string: 9

C Program to Find the Frequency of Characters in a


String
This program asks user to enter a string and a character and checks how many times the character is
repeated in the string.

To understand this example, you should have the knowledge of following C programming topics:
 C Arrays
 C Programming Strings

Example: Find the Frequency of Characters


1. #include <stdio.h>
2.
3. int main()
4. {
5. char str[1000], ch;
6. int i, frequency = 0;
7.
8. printf("Enter a string: ");
9. gets(str);
10.
11. printf("Enter a character to find the frequency: ");
12. scanf("%c",&ch);
13.
14. for(i = 0; str[i] != '\0'; ++i)
15. {
16. if(ch == str[i])
17. ++frequency;
18. }
19.
20. printf("Frequency of %c = %d", ch, frequency);
21.
22. return 0;
23. }
Output
Enter a string: This website is awesome.
Enter a character to find the frequency: e
Frequency of e = 4

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.

Finally, the frequency is printed.

C Program to Sort Elements in Lexicographical Order


(Dictionary Order)
This program sorts the 5 strings entered by the user in the lexicographical order (dictionary order).

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.

Example: Sort strings in the dictionary order


1. #include <stdio.h>
2. #include <string.h>
3.
4. int main() {
5. char str[5][50], temp[50];
6.
7. printf("Enter 5 words: ");
8. for(int i = 0; i < 5; ++i) {
9. fgets(str[i], sizeof(str[i]), stdin);
10. }
11.
12. for(int i = 0; i < 5; ++i) {
13. for(int j = i+1; j < 5 ; ++j) {
14. if(strcmp(str[i], str[j]) > 0) {
15. strcpy(temp, str[i]);
16. strcpy(str[i], str[j]);
17. strcpy(str[j], temp);
18. }
19. }
20. }
21.
22. printf("\nIn the lexicographical order: \n");
23. for(int i = 0; i < 5; ++i) {
24. fputs(str[i], stdout);
25. }
26. return 0;
27. }
Output
Enter 5 words: R programming
JavaScript
Java
C programming
C++ programming

In the lexicographical order:


C programming
C++ programming
Java
JavaScript
R programming

To solve this program, two-dimensional string str is created.

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.

C Program to Remove all Characters in a String


Except Alphabets
This program takes a strings from user and removes all characters in that string except alphabets.

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

Example: Remove Characters in String Except Alphabets


1. #include<stdio.h>
2.
3. int main()
4. {
5. char line[150];
6. int i, j;
7. printf("Enter a string: ");
8. gets(line);
9.
10. for(i = 0; line[i] != '\0'; ++i)
11. {
12. while (!( (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') ||
line[i] == '\0') )
13. {
14. for(j = i; line[j] != '\0'; ++j)
15. {
16. line[j] = line[j+1];
17. }
18. line[j] = '\0';
19. }
20. }
21. printf("Output String: ");
22. puts(line);
23. return 0;
24. }
Output

Enter a string: p2'r-o@gram84iz./

Output String: programiz

This program takes a string from the user and stored in the variable line.

C Program to Copy String Without Using strcpy()


In this article, you'll learn to copy string without using the library function strcpy().

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.

Example: Copy String Manually Without Using strcpy()


1. #include <stdio.h>
2. int main()
3. {
4. char s1[100], s2[100], i;
5.
6. printf("Enter string s1: ");
7. scanf("%s",s1);
8.
9. for(i = 0; s1[i] != '\0'; ++i)
10. {
11. s2[i] = s1[i];
12. }
13.
14. s2[i] = '\0';
15. printf("String s2: %s", s2);
16.
17. return 0;
18. }
Output
Enter String s1: programiz
String s2: programiz

This above program copies the content of string s1 to string s2 manually.

C Program to Check Whether a Character is Vowel or


Consonant
In this example, if...else statement is used to check whether an alphabet entered by the user is a vowel or a
constant.

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.

Example #1: Program to Check Vowel or consonant


1. #include <stdio.h>
2. int main()
3. {
4. char c;
5. int isLowercaseVowel, isUppercaseVowel;
6.
7. printf("Enter an alphabet: ");
8. scanf("%c",&c);
9.
10. // evaluates to 1 (true) if c is a lowercase vowel
11. isLowercaseVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
12.
13. // evaluates to 1 (true) if c is an uppercase vowel
14. isUppercaseVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
15.
16. // evaluates to 1 (true) if either isLowercaseVowel or isUppercaseVowel is true
17. if (isLowercaseVowel || isUppercaseVowel)
18. printf("%c is a vowel.", c);
19. else
20. printf("%c is a consonant.", c);
21. return 0;
22. }
Output
Enter an alphabet: G
G is a consonant.

The character entered by the user is stored in variable c.


The isLowerCaseVowel evaluates to 1 (true) if c is a lowercase vowel and 0 (false) for any other character.
Similarly, isUpperCaseVowel evaluates to 1(true) if c is an uppercase vowel and 0 (false) for any other
character.
If both isLowercaseVowel and isUppercaseVowel is equal to 0, the test expression evaluates to 0 (false) and
the entered character is a consonant.
However, if either isLowercaseVowel or isUppercaseVowel is 1 (true), the test expression evaluates to 1
(true) and the entered character is a vowel.

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.

Example #2: Program to Check Vowel or consonant


The program below asks the user to enter a character until the user enters an alphabet. Then, the program
checks whether it is a vowel or a consonant.

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

Example: Program to count vowels, consonants etc.


1. #include <stdio.h>
2.
3. int main()
4. {
5. char line[150];
6. int i, vowels, consonants, digits, spaces;
7.
8. vowels = consonants = digits = spaces = 0;
9.
10. printf("Enter a line of string: ");
11. scanf("%[^\n]", line);
12.
13. for(i=0; line[i]!='\0'; ++i)
14. {
15. if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
16. line[i]=='o' || line[i]=='u' || line[i]=='A' ||
17. line[i]=='E' || line[i]=='I' || line[i]=='O' ||
18. line[i]=='U')
19. {
20. ++vowels;
21. }
22. else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
23. {
24. ++consonants;
25. }
26. else if(line[i]>='0' && line[i]<='9')
27. {
28. ++digits;
29. }
30. else if (line[i]==' ')
31. {
32. ++spaces;
33. }
34. }
35.
36. printf("Vowels: %d",vowels);
37. printf("\nConsonants: %d",consonants);
38. printf("\nDigits: %d",digits);
39. printf("\nWhite spaces: %d", spaces);
40.
41. return 0;
42. }
Output
Enter a line of string: adfslkj34 34lkj343 34lk
Vowels: 1
Consonants: 11
Digits: 9
White spaces: 2

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.

Finally, the count is displayed on the screen.

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);

The strcmp() function takes two strings and returns an integer.

The strcmp() compares two strings character by character.


If the first character of two strings is equal, the next character of two strings are compared. This continues
until the corresponding characters of two strings are different or a null character '\0' is reached.
It is defined in the string.h header file.

Return Value from strcmp()


Return Value Remarks

0 if both strings are identical (equal)

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.

C Program to Display Characters from A to Z Using


Loop
You will learn to display the English alphabets using for loop in this example.

To understand this example, you should have the knowledge of following C programming topics:
 C if...else Statement
 C while and do...while Loop

Example #1: Program to Print English Alphabets


1. #include <stdio.h>
2. int main()
3. {
4. char c;
5.
6. for(c = 'A'; c <= 'Z'; ++c)
7. printf("%c ", c);
8.
9. return 0;
10. }
Output
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

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.

Example #2: Program to either Uppercase and Lowercase


characters
1. #include <stdio.h>
2. int main()
3. {
4. char c;
5.
6. printf("Enter u to display alphabets in uppercase.\n");
7. printf("Enter l to display alphabets in lowercase. \n");
8. scanf("%c", &c);
9.
10. if(c== 'U' || c== 'u')
11. {
12. for(c = 'A'; c <= 'Z'; ++c)
13. printf("%c ", c);
14. }
15. else if (c == 'L' || c == 'l')
16. {
17. for(c = 'a'; c <= 'z'; ++c)
18. printf("%c ", c);
19. }
20. else
21. printf("Error! You entered an invalid character.");
22. return 0;
23. }
Output
Enter u to display alphabets in uppercase.
Enter l to display alphabets in lowercase: l
a b c d e f g h i j k l m n o p q r s t u v w x y z
C Program to Remove all Characters in a String
Except Alphabets
This program takes a strings from user and removes all characters in that string except alphabets.

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

Example: Remove Characters in String Except Alphabets


1. #include<stdio.h>
2.
3. int main()
4. {
5. char line[150];
6. int i, j;
7. printf("Enter a string: ");
8. gets(line);
9.
10. for(i = 0; line[i] != '\0'; ++i)
11. {
12. while (!( (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') ||
line[i] == '\0') )
13. {
14. for(j = i; line[j] != '\0'; ++j)
15. {
16. line[j] = line[j+1];
17. }
18. line[j] = '\0';
19. }
20. }
21. printf("Output String: ");
22. puts(line);
23. return 0;
24. }
Output

Enter a string: p2'r-o@gram84iz./

Output String: programiz

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

Example: Reverse a sentence using recursion


1. /* Example to reverse a sentence entered by user without using strings. */
2.
3. #include <stdio.h>
4. void reverseSentence();
5.
6. int main()
7. {
8. printf("Enter a sentence: ");
9. reverseSentence();
10.
11. return 0;
12. }
13.
14. void reverseSentence()
15. {
16. char c;
17. scanf("%c", &c);
18.
19. if( c != '\n')
20. {
21. reverseSentence();
22. printf("%c",c);
23. }
24. }
Output
Enter a sentence: margorp emosewa
awesome program

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.

This process goes on until user enters '\n'.

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.

You might also like