String
Strings are actually
The following declaration and initialization create a string consisting of the word “Hello”. To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word “Hello.”
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −
How to declare a string?
Before you can work with strings, you need to declare them first. Since string is an array of characters. You declare strings in a similar way like you do with arrays.
If you don’t know what arrays are, we recommend you to check C arrays.
Here’s how you declare a string:
char s[5];
How to initialize strings?
You can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
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 a whitespace(space, newline, tab etc.).
Example 1: scanf() to read a string
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
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 Ritche.
How to read a line of text?
You can use gets()
function to read a line of string. And, you can use puts()
to display the string.
Example 2: gets() and puts()
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
When you run the program, the output will be:
Enter name: Tom Hanks Name: Tom Hanks
Passing Strings to Function
Strings can be passed to a function in a similar way as arrays. Learn more about passing array to a function.
Example 3: Passing string to a Function
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
gets(str);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
Strings and Pointers
Similar like arrays, string names are “decayed” to pointers. Hence, you can use pointer with the same name as string 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
#include <stdio.h>
int main(void) {
char name[] = "Harry Potter";
printf("%c", *name); // Output: H
printf("%c", *(name+1)); // Output: a
printf("%c", *(name+7)); // Output: o
char *namePtr;
namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}
Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the ‘\0’ at the end of the string when it initializes the array.
#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings −
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */ len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
The following example uses some of the above-mentioned functions −
When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
C supports a wide range of functions that manipulate null-terminated strings −
Sr.No. | Function & Purpose |
---|---|
1 | strcpy(s1, s2);Copies string s2 into string s1. |
2 | strcat(s1, s2);Concatenates string s2 onto the end of string s1. |
3 | strlen(s1);Returns the length of string s1. |
4 | strcmp(s1, s2);Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. |
5 | strchr(s1, ch);Returns a pointer to the first occurrence of character ch in string s1. |
6 | strstr(s1, s2);Returns a pointer to the first occurrence of string s2 in string s1. |
Example: Find the Frequency of Characters
#include <stdio.h>
int main()
{
char str[1000], ch;
int i, frequency = 0;
printf("Enter a string: ");
gets(str);
printf("Enter a character to find the frequency: ");
scanf("%c",&ch);
for(i = 0; str[i] != '\0'; ++i)
{
if(ch == str[i])
++frequency;
}
printf("Frequency of %c = %d", ch, frequency);
return 0;
}
Output
Enter a string: This website is awesome. Enter a character to find the frequency: e Frequency of e = 4
Program to Print ASCII Value
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
// Reads character input from the user
scanf("%c", &c);
// %d displays the integer value of a character
// %c displays the actual character
printf("ASCII value of %c = %d", c, c);
return 0;
}
Output
Enter a character: G ASCII value of G = 71
Example: Program to Check Alphabet or Not
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
if( (c>='a' && c<='z') || (c>='A' && c<='Z'))
printf("%c is an alphabet.",c);
else
printf("%c is not an alphabet.",c);
return 0;
}
Output
Enter a character: * * is not an alphabet
Program to Check Vowel or consonant
#include <stdio.h>
int main()
{
char c;
int isLowercaseVowel, isUppercaseVowel;
printf("Enter an alphabet: ");
scanf("%c",&c);
// evaluates to 1 (true) if c is a lowercase vowel
isLowercaseVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
// evaluates to 1 (true) if c is an uppercase vowel
isUppercaseVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
// evaluates to 1 (true) if either isLowercaseVowel or isUppercaseVowel is true
if (isLowercaseVowel || isUppercaseVowel)
printf("%c is a vowel.", c);
else
printf("%c is a consonant.", c);
return 0;
}
Output
Enter an alphabet: G G is a consonant.
Remove Characters in String Except Alphabets
#include<stdio.h>
int main()
{
char line[150];
int i, j;
printf("Enter a string: ");
gets(line);
for(i = 0; line[i] != '\0'; ++i)
{
while (!( (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A'
&& line[i] <= 'Z') || line[i] == '\0') )
{
for(j = i; line[j] != '\0'; ++j)
{
line[j] = line[j+1];
}
line[j] = '\0';
}
}
printf("Output String: ");
puts(line);
return 0;
}
Output
Enter a string: p2'r-o@gram84iz./ Output String: programiz
Program to Display English Alphabets
#include <stdio.h>
int main()
{
char c;
for(c = 'A'; c <= 'Z'; ++c)
printf("%c ", c);
return 0;
}
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
Program to Display English Alphabets in Uppercase and Lowercase
#include <stdio.h>
int main()
{
char c;
printf("Enter u to display alphabets in uppercase. And enter l to display alphabets in lowercase: ");
scanf("%c", &c);
if(c== 'U' || c== 'u')
{
for(c = 'A'; c <= 'Z'; ++c)
printf("%c ", c);
}
else if (c == 'L' || c == 'l')
{
for(c = 'a'; c <= 'z'; ++c)
printf("%c ", c);
}
else
printf("Error! You entered invalid character.");
return 0;
}
Output
Enter u to display alphabets in uppercase. And 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
Calculate Length of String without Using strlen() Function
#include <stdio.h>
int main()
{
char s[1000];
int i;
printf("Enter a string: ");
scanf("%s", s);
for(i = 0; s[i] != '\0'; ++i);
printf("Length of string: %d", i);
return 0;
}
Output
Enter a string: Programiz Length of string: 9
Copy String Manually Without Using strcpy()
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.
#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}
Output
Enter String s1: programiz
String s2: programiz
Program to Check if a given String is Palindrome
#include <stdio.h>
#include <string.h>
void main()
{
char string[25], reverse_string[25] = {'\0'};
int i, length = 0, flag = 0;
printf("Enter a string \n");
gets(string);
/* keep going through each character of the string till its end */
for (i = 0; string[i] != '\0'; i++)
{
length++;
}
for (i = length - 1; i >= 0; i--)
{
reverse_string[length - i - 1] = string[i];
}
/*
* Compare the input string and its reverse. If both are equal
* then the input string is palindrome.
*/
for (i = 0; i < length; i++)
{
if (reverse_string[i] == string[i])
flag = 1;
else
flag = 0;
}
if (flag == 1)
printf("%s is a palindrome \n", string);
else
printf("%s is not a palindrome \n", string);
}
Enter a string
sanfoundry
sanfoundry is not a palindrome
Enter a string
malayalam
malayalam is a palindrome
C Program to Accepts two Strings & Compare them
#include <stdio.h>
void main()
{
int count1 = 0, count2 = 0, flag = 0, i;
char string1[10], string2[10];
printf("Enter a string:");
gets(string1);
printf("Enter another string:");
gets(string2);
/* Count the number of characters in string1 */
while (string1[count1] != '\0')
count1++;
/* Count the number of characters in string2 */
while (string2[count2] != '\0')
count2++;
i = 0;
while ((i < count1) && (i < count2))
{
if (string1[i] == string2[i])
{
i++;
continue;
}
if (string1[i] < string2[i])
{
flag = -1;
break;
}
if (string1[i] > string2[i])
{
flag = 1;
break;
}
}
if (flag == 0)
printf("Both strings are equal \n");
if (flag == 1)
printf("String1 is greater than string2 \n", string1, string2);
if (flag == -1)
printf("String1 is less than string2 \n", string1, string2);
}
Enter a string: hello
Enter another string: world
String1 is less than string2
Enter a string:object
Enter another string:class
String1 is greater than string2
Enter a string:object
Enter another string:object
Both strings are equal
Program to Replace Lowercase Characters by Uppercase & Vice-Versa
#include <stdio.h>
#include <ctype.h>
void main()
{
char sentence[100];
int count, ch, i;
printf("Enter a sentence \n");
for (i = 0;(sentence[i] = getchar()) != '\n'; i++)
{
;
}
sentence[i] = '\0';
/* shows the number of chars accepted in a sentence */
count = i;
printf("The given sentence is : %s", sentence);
printf("\n Case changed sentence is: ");
for (i = 0; i < count; i++)
{
ch = islower(sentence[i])? toupper(sentence[i]) :
tolower(sentence[i]);
putchar(ch);
}
}
Enter a sentence
wELCOME tO sANFOUNDRY
The given sentence is : wELCOME tO sANFOUNDRY
Case changed sentence is: Welcome To Sanfoundry
Program to Count Number of Words in a given Text or Sentence
#include <stdio.h>
#include <string.h>
void main()
{
char s[200];
int count = 0, i;
printf("enter the string\n");
scanf("%[^\n]s", s);
for (i = 0;s[i] != '\0';i++)
{
if (s[i] == ' ')
count++;
}
printf("number of words in given string are: %d\n", count + 1);
}
enter the string
welcome to sanfoundry's c-programming class!
number of words in given string are: 5
Program to Find the Frequency of the Word ‘the’ in a given Sentence
#include <stdio.h>
void main()
{
int count = 0, i, times = 0, t, h, e, space;
char string[100];
puts("Enter a string:");
gets(string);
/* Traverse the string to count the number of characters */
while (string[count] != '\0')
{
count++;
}
/* Finding the frequency of the word 'the' */
for (i = 0; i <= count - 3; i++)
{
t =(string[i] == 't' || string[i] == 'T');
h =(string[i + 1] == 'h' || string[i + 1] == 'H');
e =(string[i + 2] == 'e'|| string[i + 2] == 'E');
space =(string[i + 3] == ' ' || string[i + 3] == '\0');
if ((t && h && e && space) == 1)
times++;
}
printf("Frequency of the word 'the' is %d\n", times);
}
Enter a string:
The gandhi jayanthi is celeberated on october 2 is the day
that he has born.
Frequency of the word 'the' is 2
Program to Calculate the Net Salary.
#include <stdio.h>
main()
{
float basic_sal, da, hra, pf, gross_sal, net_sal;
printf("\nEnter basic salary of the employee: Rs. ");
scanf("%f", &basic_sal);
da = (basic_sal * 25)/100;
hra = (basic_sal * 15)/100;
gross_sal = basic_sal + da + hra;
pf = (gross_sal * 10)/100;
net_sal = gross_sal - pf;
printf("\n\nNet Salary: Rs. %.2f", net_sal);
getch();
}