In C programming, a string is a sequence of characters terminated with a
null character \0.
________________________________________________________
For example:
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?
Syntax:
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.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0’};
char c[5] = {'a', 'b', 'c', 'd', ‘e’};
//invalid declaration
String Initialization in C
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 Ritchie
#include<stdio.h>
int main()
{
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[11]="javatpoint";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}
Output
Char Array Value is:
javatpoint
String Literal Value is:
javatpoint
gets() and puts()
Functions gets() and puts() are two string functions to take string input from the
user and display it respectively.
#include<stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Note:
Though, gets() and
puts() function handle
strings, both these
functions are defined in
"stdio.h" header file.
You can use the fgets() function to read a line of string.
Here, we have used fgets() function to read a string from the user.
The sizeof(name) results to 30.
Hence it take a maximum of 30 characters as input which is the size of the
name string.
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output
Enter name: Tom Hanks
Name: Tom Hanks
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.
Copy one String into Another
#include <stdio.h>
int main() {
char s1[100], s2[100], i;
printf("Enter string s1: ");
//fgets(s1, sizeof(s1), stdin);
gets(s1);
for (i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
}
Output:
Enter string s1: abc
String s2: abc
Calculate Length of String
#include <stdio.h>
int main()
{
char s[] = "Programming is fun";
int i;
for (i = 0; s[i] != '\0'; i++);
printf("Length of the string: %d", i);
return 0;
}
Output:
Length of the string: 18
Find the Frequency of a Character in given string
#include <stdio.h>
int main()
{
char str[1000], ch;
int count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Enter a character to find its frequency: ");
scanf("%c", &ch);
for (int i = 0; str[i] != '\0’; i++)
{
if (ch == str[i])
++count;
}
printf("Frequency of %c = %d", ch, count);
return 0;
}
Output
Enter a string:
This website is awesome.
Enter a character to find its
frequency: e
Frequency of e = 4
Program to count vowels, consonants etc.
#include <stdio.h>
int main() {
char line[150];
int vowels, consonant, digit, space;
vowels = consonant = digit = space = 0;
printf("Enter a line of string: ");
fgets(line, sizeof(line), stdin);
for (int i = 0; line[i] != '\0'; ++i)
{
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u' || line[i] == 'A' ||
line[i] == 'E' || line[i] == 'I' || line[i] == 'O' ||
line[i] == 'U’)
{
++vowels;
}
else if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z’))
{
++consonant;
} else if (line[i] >= '0' && line[i] <= '9’)
{
++digit;
}
else if (line[i] >= '0' && line[i] <= '9’)
{
++digit;
}
else if (line[i] == ‘ ‘)
{
++space;
}
}
printf("Vowels: %d", vowels);
printf("\nConsonants: %d", consonant);
printf("\nDigits: %d", digit);
printf("\nWhite spaces: %d", space);
return 0;
}
You need to often manipulate strings according to the need of
a problem we have to different operation on string like
concatenation , reverse , compare string.
Most of the time string manipulation can be done manually but,
this makes programming complex and large.
To solve this problem , C supports a large
number of string handling functions in
the standard library "string.h".
No.
Function
Description
1)
strlen(string_name)
returns the length of string name.
2)
strcpy(destination, source)
copies the contents of source string to destination string.
3)
strcat(first_string, second_string)
concats or joins first string with second string. The result of
the string is stored in first string.
4)
strcmp(first_string, second_string)
compares the first string with second string. If both strings are
same, it returns 0.
5)
strrev(string)
returns reverse string.
6)
strlwr(string)
returns string characters in lowercase.
7)
strupr(string)
returns string characters in uppercase.
Compare String
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);
//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Output:
Enter 1st string: hello
Enter 2nd string: hello
Strings are equal
Reverse String
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str); //reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:
Enter string: javatpoint
String is: javatpoint
Reverse String is: tnioptavaj
String Lowercase
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
Output:
Enter string: JAVATpoint
String is: JAVATpoint
Lower String is: javatpoint
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
C Programming allows us to perform mathematical operations through the
functions defined in <math.h> header file.
The <math.h> header file contains various methods for performing mathematical
operations
No.
Function
Description
1)
ceil(number)
rounds up the given number. It returns the integer value which is greater
than or equal to given number.
2)
floor(number)
rounds down the given number. It returns the integer value which is less
than or equal to given number.
3)
sqrt(number)
returns the square root of given number.
4)
pow(base, exponent)
returns the power of given number.
5)
abs(number)
returns the absolute value of given number.
simple example of math functions found in math.h header file.
#include<stdio.h>
#include <math.h>
int main()
{
printf("\n Ceil :%f", ceil(3.6));
printf("\n Ceil :%f", ceil(3.3));
printf("\n floor:%f", floor(3.6));
printf("\n floor:%f", floor(3.2));
printf("\n Squre Root : %f", sqrt(16));
printf("\n Power :%f", pow(2,3));
return 0;
}
Output :
Ceil :4.000000
Ceil :4.000000
floor:3.000000
floor:3.000000
Squre Root : 4.000000
Power :8.000000
Arrays of Strings
To create an array of strings, use a two-dimensional character array.
The size of the left dimension determines the number of strings, and the
size of the right dimension specifies the maximum length of each string.
Syntax:
char str_array[30][80];
Example:
char city[3][10]={“Pune”,”Mumbai”,”Satara”};
The following declares an array of 3 strings, each with a maximum
length
of 10 characters:
Program to accept and display n names.
#include<stdio.h>
int main()
{
char names[10][20];
int i,n;
printf("\nEnter how many names : ");
scanf("%d",&n); /*Accept n names*/
for(i=0;i<n;i++)
{
printf("\nEnter name%d:",i);
gets(names[i]);} /*Displaying n names*/
for(i=0;i<n;i++)
{
puts(names[i]);
}
}
Output:
Enter how many names : 2
Enter name 0: Gauri
Enter name 1: Anuja
Pointers and Strings
A string is an array of characters. Thus pointer notation can be
applied to the characters in strings.
char tv[20] = “ONIDA”;
char *p = tv;
For the first statement, the compiler allocates 20 bytes of memory and
stores in the first six bytes the char values.
write a program to find the length of the string and print
the string in reverse order using pointer notation
#include <stdio.h>
main()
{
int n, i;
char tv[20] = “ABCDE”;
char *p = tv, *q;
/* p = &tv[0], q is a pointer */
q = p;
while (*p != ‘\0’)
p++;
n = p - q;
/* length of the string */
--p;
/* make p point to the last character A in the string */
printf (“\nLength of the string is %d”, n);
printf (“\nString in reverse order: \n”);
for (i=0; i<n; i++)
{
putchar (*p);
p--;
}
}
Output:
Length of the string is 5
String in reverse order: EDCBA
References for Theory
https://www.programiz.com/c-program
ming/c-strings
https://www.tutorialspoint.com/cprogra
mming/c_strings.htm
https://www.geeksforgeeks.org/strings
-in-c-2/
https://www.javatpoint.com/c-strings
0 Comments