Wednesday 10 August 2011

Strings

Definition:

String is a collection of characters that is treated as a single data item and terminated by null character'\0'.

Unfortunately String data type is not available in C language but we use character array is treated as String.

A string is actually one-dimensional array of characters in C language.

Syntax:

char variable[size];

Example :
char s[9]="Namasthe";
 or
char s[9]="Namasthe\0";

or
char s[9]={'N','a','m','a','s','t','h','e','\0'};

The string "Namasthe" contains 9 characters including '\0' character which is automatically added by the compiler at the end of the string.

Note:
char s[3]="Raj"; //Error due to we must specify the size for null character also '\0'


Accessing the Strings:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
 char s[20];

 printf("Enter a string");
 scanf("%[^\n]",&str);
 printf("%s",str);
 return 0;
}


Another method to read character string with white spaces from terminal is gets() function.

 char s[20];
 gets(s);
 printf("%s",s);

Ex2:

#include<stdio.h>
#include<conio.h>
void main()
{
 char a[10],b[10]; //array declaration of size 10
 clrscr();
 printf("enter a string");
 scanf("%s",&a);
 strcpy(b,a);//copies string a to b
 strrev(b);//reverses string b
 if(strcmp(a,b)==0)//compares if the original &                                            // revers strings are same
 {
  printf("\n%s is a palindrome",a);
 }
else
 {
 printf("\n%s is not a palindrome",a);
 }
getch();
}


------------------------------------------------------------------------------------------------------------

                                                                    Review Questions
Short answers type
1)     Define a string. How to declare & initialize  string.
2)     List the various string operations.
3)     Explain the function of strcmp() & stricmp().

Essay type questions

1)     Explain the various string functions with the help of the program.
2)     Write a program funds the length of the given string.
3)     Explain any eight string functions used in ‘C’ language.
Write a C program to read a string and its each character in a new line.

Next: String Handling Functions

You may like the following posts:
Strings ppt

No comments:

Post a Comment