Tuesday 1 October 2013

String in C

String:- The array of characters is known as string.
string is always terminated by the null.

Ex:- char a[5];
 it contains the string of length 5 and also terminated by null.

                   


initialization of char array:

char a[] = {'a','b','c','d','\0'};
char a[5]=abcd;

Take string from user:-

char a[10];
scanf("%s",a);

Difference between scanf() and gets():-
 the compiler does not read the value after the white spaces in scanf but in gets method compiler does read value even white space occurs or not.

Ex:-
char a[30];
scanf("%s",a);
gets(a);

we take input :  C tutorials

scanf take only  C
gets take both C tutorials.

Read a String

main()
{
char a[10] , i=0;
printf("enter the string");
scanf("%s",a);
while(a[i] != '\0')
{
printf("%c",a[i]);
i++;
}
}

it prints the inserted string character by character.

EX:-
main()
{
char a[10];
printf("enter the name");
gets(name); //taking the string a s input
puts(name);// display the string
}

Passing string to function:-

Ex:-
void print(char c[]);
void main()
{
char c[20];
printf("enter the name");
gets(c);   //take the string
print(c);  // call the print method
}
void print(char c[])
{
puts(c); // print the string
}


String Library Functions:-C supports various type of string handling functions present in the string.h file.
for using string function we must include string.h file.

some string handling functions are as follows:

strlen()       find the length of string
strcpy()      copy the string
strcmp()     compare the two string
strcat()      concatenate the two string
strlwr()     convert string to lower case
strupr()     convert string to upper case

EX:-
char a[50];
int i;
gets(a);
i=strlen(a);
printf("%d",i); // print the length of string



all examples of string are discussed in example section.

No comments :

Post a Comment