Strings are defined as an
array of characters. The difference between a character array and a string is that the string is terminated with a special character ‘\0’.
- The string can be defined as the one-dimensional array of characters terminated by a null ('\0’).
- The character array or the string is used to manipulate text such as word or sentences.
- Each character in the array occupies one byte of memory.
- The termination character ('\0') is important in a string since it is the only way to identify where the string ends
Declaration of strings: Declaring a string is as simple as
declaring a one dimensional array. Below is the basic syntax for declaring a
string.
char str_name[size];
In
the above syntax str_name is any name given to the string variable and size is
used define the length of the string, i.e the number of characters strings will
store. Please keep in mind that there is an extra terminating character which
is the Null character ('\0') used to indicate termination of string which
differs strings from normal character arrays.
Initializing a String: A string can be initialized in different
ways. We will explain this with the help of an example. Below is an example to
declare a string with name as str and initialize it with "mec".
1. char str[] =
"mec";
2. char str[50] =
"mec";
3. char str[] =
{'m','e','c' ,'\0'};
4. char str[4] =
{'m','e','c','\0'};
String input output:printf and scanf with %s format specifier is
used for printing and reading. However basic scanf statement will read up to
space.The gets(S) function can be used to read a line and store it in string S.gets is deprecated because it's dangerous, it may cause buffer overflow.
instead of gets you can also use scanf("%[^\n]",s), for reading a string s.Other choices are getline() and fgets().The function getchar() can be used to read a single character.
For printing strings printf with %s format character can be used.puts and fputs can also be used.
scanf and printf with %s
#include<stdio.h>
int main() {
char s1[100];
printf("Enter a string:::");
scanf("%s",s1);
printf("string read using scanf:%s",s1);
}
int main() {
char s1[100];
printf("Enter a string:::");
scanf("%s",s1);
printf("string read using scanf:%s",s1);
}
O/P
Enter a string:::mec thrikakkara
string read using scanf:mec
Note that scanf will read characters upto space.
gets() and puts()---- fgets() and fputs() functions
The gets() and puts() functions are declared in the header file stdio.h. Both the functions are involved in the input/output operations of the strings.Similarly fgets() and fputs() can be used to read and write from streams( files).
gets() and fgets() function
The gets() function enables the user to enter some characters followed by the enter key. All the characters entered by the user get stored in a character array. The null character is added to the array to make it a string. The gets() allows the user to enter the space-separated strings. It returns the string entered by the user.
Declaration
char[] gets(char[]);
Reading string using gets()
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
Output
Enter the string? mec is best
You entered mec is the best
#include<stdio.h>
void main()
{
char str[10];
printf("Enter the string? ");
fgets(str, 10, stdin);
printf("%s", str);
}
Output
Enter the string? mec is the best
The gets() function is risky to use since it doesn't perform any array bound checking and keep reading the characters until the new line (enter) is encountered. It suffers from buffer overflow, which can be avoided by using fgets(). The fgets() makes sure that not more than the maximum limit of characters are read. Consider the following example.
#include<stdio.h>
void main()
{
char str[10];
printf("Enter the string? ");
fgets(str, 10, stdin);
printf("%s", str);
}
Output
Enter the string? mec is the best
mec is the
puts() and fputs() function
The puts() function is very much similar to printf() function. The puts() function is used to print the string on the console which is previously read by using gets() or scanf() function. The puts() function returns an integer value representing the number of characters being printed on the console. Since, it prints an additional newline character with the string, which moves the cursor to the new line on the console, the integer value returned by puts() will always be equal to the number of characters present in the string plus 1.
Declaration
int puts(char[])
The function fputs can also be used to write a string to a specified stream with out the null character.
int fputs(const char *str, FILE *stream)
Eg:fputs(str,stdout) will write the string to standard output.
Let's see an example to read a string using gets() and print it on the console using puts().
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
Output:
Enter your name: Aditi Binu
Eg:fputs(str,stdout) will write the string to standard output.
Let's see an example to read a string using gets() and print it on the console using puts().
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
Output:
Enter your name: Aditi Binu
Your name is: Aditi Binu
strlen() function
The strlen() function returns the length of the given string. It doesn't count null character '\0'.
strcmp()
The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are equal.
Here, we are using gets() function which reads string from the console.
#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
Count the occurrence of a character in a string
#include <stdio.h>
#include <string.h>
void main()
{
char s[100],c;
int i,n=0;
printf("Enter a string...\n");
scanf("%[^\n]",s); // instead of gets(s)
printf("Enter the character to search...\n");
scanf(" %c",&c); // leave a space before %c which will eat special characters
for(i=0;i<strlen(s);i++)
if(s[i]==c) n++;
printf("Number of occurrence=%d\n",n);
}
Check whether the given character is present in a string ( university question)
string.h
Various string handling functions defined in C can be used by including the header file string.h
The most commonly used functions in the string library string.h are:
strcat - concatenate two strings.
strchr - string scanning operation.
strcmp - compare two strings.
strcpy - copy a string.
strlen - get string length.
strncat - concatenate one string with part of
another.
strncmp - compare parts of two strings.
strncpy - copy part of a string.
strrchr - string scanning operation.
strstr - Find a substring.
strlwr-convert string to lower case.
strupr-convert string to upper case.
strrev-reverse a string
The strlen() function returns the length of the given string. It doesn't count null character '\0'.
#include<stdio.h>
#include <string.h>
int main(){
char s[20]={'b', 'i', 'n', 'u','\0'};
char s1[20]="mec";
printf("Length of string s is: %lu\n",strlen(s));
printf("Length of string s1 is: %lu\n",strlen(s1));
return 0;
}
O/P
Length of string s is: 4
Length of string s1 is: 3
strcpy()
The strcpy(destination, source) function copies the source string in to the destination string.
strcat()
The strcat(first_string, second_string) function concatenates two strings and result is returned to first_string.
The strcpy(destination, source) function copies the source string in to the destination string.
#include<stdio.h>
#include <string.h>
int main(){
char s1[20]="mec is the best";
char s2[20];
strcpy(s2,s1);
printf("Content of second string s2 is: %s",s2);
return 0;
}
O/P
Content of second string s2 is: mec is the best
strcat()
The strcat(first_string, second_string) function concatenates two strings and result is returned to first_string.
#include<stdio.h>
#include <string.h>
int main(){
char s1[20]="mec";
char s2[20]=" thrikakara";
strcat(s1,s2);
printf("Content of the string s1 is: %s",s1);
return 0;
}
O/P
Content of the string s1 is: mec thrikakara
strcmp()
The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are equal.
Here, we are using gets() function which reads string from the console.
#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
strrev()
The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev() function.
#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: mec
strrev()
The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev() function.
#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: mec
String is: mec
Reverse String is: cem
Note:
Functions like strrev(),strlwr(),strupr() etc will work in ANSI C ( Turbo C) and are not available in standard C-GCC compiler.No standard operators for
string assignment,concatenation and comparison ( like in Python or Java). Strings in C are
just arrays of characters only.
Sample
Programs
C program to read and print a string
#include<stdio.h>
int main()
{
// declaring string
char str[50];
// reading string
scanf("%s",str);
// print string
printf("%s",str);
return 0;
}
read a string and print the characters backwards
#include<stdio.h>
#include<string.h>
int main() {
char S[100];
int l, i;
printf("Enter the string..\n");
gets(S);
l = strlen(S);
printf("\nbackward\n");
for (i = l-1; i >= 0; --i)
printf(" %c",S[i]);
}
Find the length of a string without using built in functions(uq).
#include<stdio.h>
int main()
{
char s[100];
int i,len;
printf("Enter the string..\n");
scanf("%[^\n]",s);
for(i=0;s[i]!='\0';i++);
len=i;
printf("Length of the string=%d",len);
}
int main()
{
char s[100];
int i,len;
printf("Enter the string..\n");
scanf("%[^\n]",s);
for(i=0;s[i]!='\0';i++);
len=i;
printf("Length of the string=%d",len);
}
check
whether the given string is palindrome(strrev will not work in gcc)
#include<stdio.h>
#include<string.h>
int main() {
char s[100],rs[100];
int l, i;
printf("Enter the string..\n");
gets(s);
strcpy(rs,s); // copying the string
s to rs using strcpy function
//reversing the string using built in function
strrev
strrev(rs)
//comparing the strings using strcmp function
if ( strcmp(s,rs)==0)
printf("String is palindrome")
else
printf("Not palindrome");
}
Palindrome checking -strrev and strcpy is done using a loop
#include<stdio.h>
#include<string.h>
int main() {
char s[100],rs[100];
int l, i,j;
printf("Enter the string..\n");
gets(s);
//reverse and copy
for(i=strlen(s)-1,j=0;i>=0;i--,j++)
rs[j]=s[i];
rs[j]='\0';
//comparing the strings using strcmp function
printf("Reversed string is \n");
puts(rs);
if ( strcmp(s,rs)==0)
printf("String is palindrome");
else
printf("Not palindrome");
}
Palindrome checking without using built in functions( do not use string.h) ( university qn)
#include<stdio.h>
int main() {
char s[100],rs[100];
int flag=1, i,j,len=0;
printf("Enter the string..\n");
scanf("%[^\n]",s);
//check for palindrome
for(i=0;s[i]!='\0';i++,len++);//finding length of the string
printf("length of the string is %d\n",len);
for(i=0,j=len-1;i<=j;i++,j--)
if(s[i]!=s[j]) {flag=0;break;}
if ( flag)
printf("String is palindrome\n");
else
printf("Not palindrome\n");
}
Count the occurrence of a character in a string
#include <stdio.h>
#include <string.h>
void main()
{
char s[100],c;
int i,n=0;
printf("Enter a string...\n");
scanf("%[^\n]",s); // instead of gets(s)
printf("Enter the character to search...\n");
scanf(" %c",&c); // leave a space before %c which will eat special characters
for(i=0;i<strlen(s);i++)
if(s[i]==c) n++;
printf("Number of occurrence=%d\n",n);
}
Check whether the given character is present in a string ( university question)
#include <stdio.h>
#include <string.h>
void main()
{
char s[100],c;
int i,f=0;
printf("Enter a string...\n");
scanf("%[^\n]",s); // instead of gets(s)
printf("Enter the character to search...\n");
scanf(" %c",&c); // leave a space before %c which will eat special characters
for(i=0;i<strlen(s);i++)
if(s[i]==c) {f=1;break;};
if(f)
printf("Given character is present in the string");
else
printf("Given Character is not present in the string\n");
}
Concatenating two strings with out using built in functions( university question)
#include <stdio.h>
int main()
{
int i,j;
char s1[100],s2[100];
printf("Enter the string1...\n");
scanf("%[^\n]",s1);
getchar();
printf("Enter the string2...\n");
scanf("%[^\n]",s2);
for(i=0;s1[i]!='\0';i++); // empty for loop for finding length
for(i=i,j=0;s2[j]!='\0';j++,i++)
s1[i]=s2[j];
s1[i]='\0';
printf("The concatenated string...:%s\n",s1);
}
Sorting list of names
#include <stdio.h>
#include <string.h>
main()
{
char names[100][50],temp[50];
int i,j,n;
printf("Enter the number of names..\n");
scanf("%d",&n);
printf("Enter names..\n");
for(i=0;i<n;i++)
{
getchar();
scanf("%[^\n]",names[i]);
}
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if (strcmp(names[j],names[j+1])>0)
{
strcpy(temp,names[i]);
strcpy(names[i],names[j]);
strcpy(names[j],temp);
}
printf("List of names in sorted order\n");
for(i=0;i<n;i++)
printf("%s\n",names[i]);
}
Count the number of vowels, consonants , digits and spaces in a string.
#include <stdio.h>
int main()
{
char str[150];
int i, vowels, consonants, digits, spaces;
vowels = consonants = digits = spaces = 0;
printf("Enter a string: ");
scanf("%[^\n]", str);
for(i=0; str[i]!='\0'; ++i)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
str[i]=='o' || str[i]=='u' || str[i]=='A' ||
str[i]=='E' || str[i]=='I' || str[i]=='O' ||
str[i]=='U')
{
++vowels;
}
else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z'))
{
++consonants;
}
else if(str[i]>='0' && str[i]<='9')
{
++digits;
}
else if (str[i]==' ')
{
++spaces;
}
}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d\n", spaces);
}
#include <stdio.h>
int main()
{
char str[150];
int i, vowels, consonants, digits, spaces;
vowels = consonants = digits = spaces = 0;
printf("Enter a string: ");
scanf("%[^\n]", str);
for(i=0; str[i]!='\0'; ++i)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
str[i]=='o' || str[i]=='u' || str[i]=='A' ||
str[i]=='E' || str[i]=='I' || str[i]=='O' ||
str[i]=='U')
{
++vowels;
}
else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z'))
{
++consonants;
}
else if(str[i]>='0' && str[i]<='9')
{
++digits;
}
else if (str[i]==' ')
{
++spaces;
}
}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d\n", spaces);
}
Replacing a character with another in a string(university question)
#include <stdio.h>
#include <string.h>
int main()
{
char s[100],c,nc;
int i;
printf("Enter the string..:\n");
scanf("%[^\n]",s);
printf("Enter the character to replace..\n");
scanf(" %c",&c);
printf("Enter the new character ....\n");
scanf(" %c",&nc);
for(i=0;i<strlen(s);i++)
{
if(s[i]==c)
s[i]=nc;
}
printf("New string after replacement is \n");
printf("%s\n",s);
}
#include <stdio.h>
#include <string.h>
int main()
{
char s[100],c,nc;
int i;
printf("Enter the string..:\n");
scanf("%[^\n]",s);
printf("Enter the character to replace..\n");
scanf(" %c",&c);
printf("Enter the new character ....\n");
scanf(" %c",&nc);
for(i=0;i<strlen(s);i++)
{
if(s[i]==c)
s[i]=nc;
}
printf("New string after replacement is \n");
printf("%s\n",s);
}
Reverse a string with out using string functions.(uq)
#include <stdio.h>
int main()
{
char str[150];
char t;
int i,j,len;
printf("Enter a string: ");
scanf("%[^\n]", str);
for(i=0;str[i]!='\0';i++);
len=i;
for(i=0,j=len-1;i<len/2;i++,j--)
{
t=str[i];
str[i]=str[j];
str[j]=t;
}
printf("reversed string is \n");
printf("%s",str);
}
int main()
{
char str[150];
char t;
int i,j,len;
printf("Enter a string: ");
scanf("%[^\n]", str);
for(i=0;str[i]!='\0';i++);
len=i;
for(i=0,j=len-1;i<len/2;i++,j--)
{
t=str[i];
str[i]=str[j];
str[j]=t;
}
printf("reversed string is \n");
printf("%s",str);
}
programs to try
1.Read a string and print the characters backward.
2.check whether the given string is palindrome.(use built in functions)
3.count the occurrence of a character in a string.(uq)
4,Write a C program to read a sentence through keyboard and to display the count of white
spaces in the given sentence.(uq)
5.Write a C program to read an English Alphabet through keyboard and display whether
the given Alphabet is in upper case or lower case.(uq)
6.Without using any builtin string processing function like strlen, strcat etc., write a
program to concatenate two strings.(uq)
7.count the number of vowels, consonants , digits and spaces in a string(uq)
8.Read list of names and sort the names in alphabetical order.
9.Toggle the case of every alphabet in the input string.
10.Write a C program to read an English Alphabet through keyboard and display whether
the given Alphabet is in upper case or lower case
12.Check for palindrome with out using built in functions.
13..Copy one string to another.
14.Count the number of words.
15.Print a substring ( read position and length)
16.Count all the occurrence of a particular word.
17.Remove all occurrence of a word from a sentence.
18.Check whether a word is present in a string.
19.Insert a word before a particular word.
20.Read a word and print the characters in alphabetical order.
20.Read a word and print the characters in alphabetical order.
21.Remove characters other than alphabet from a string
22.Reverse a string with out using string functions.(uq)
23.Find the length of a string without using built in functions(uq).
hey friends i found a new proagraing language learn php
ReplyDeletehey friends i found a new proagraing language learn php
ReplyDelete