Monday, 25 February 2013

String functions










Read This:
strncpy()
strncat()
strstr()
strlen()
Predefined function defined in string.h .
Returns the length of string .
Syntax:  returntype  strlen(string_var_name)

#include<stdio.h>
main()
{
    char ar[20]=“Arvind”;
    printf(“%d”,strlen(ar));
 }
strcmp()
Used to compare two strings characterwise
syntax: strcmp(s1,s2)






#include<stdio.h>
#include<string.h>
void main()
{  int i;
  char name[20]=“home";
  char name1[20]="sweet";
  i=strcmp(name,name1);   // name<name1
  printf("%d”,i);
} 
-11

strcpy()

Defined in string.h
Used to copy one string to another string
Syntax: strcpy(string1,string2)

Ex
#include<stdio.h>
#include<string.h>
void main()
{   char name1[20];
    char name2[20]=“harry”;
    strcpy(name1,name2);
    printf(“%s”,name1);
 } 
harry

strcat( )
Also defined in string.h
Syntax:strcat(string1,string2)
Append string2 at the end of string1.
Ex.
#include<stdio.h>
#include<string.h>
main( )
{int i;
  char name1[20]="home";
  char name2[20]="sweet";
  strcat(name2,name1);  
  printf("%s",name1);   }
sweethome




Strings

What is string?

Array of  characters.
‘\0’ in string signifies end of the string in memory.
Strings is enclosed within double quotes.
Initializing Strings
2 ways
char month1[]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’};
char month1[]=“january”;
Example




Array of strings
#include<stdio.h>
const int Num=5;
const int length=9;
main()
{
int j;
char Names[Num][length]={“Tejaswi”,”Prasad”,
                                ”Prashant”,”Anand”, “Priya”};
for(j=0;j<Num;j++) printf(“%s\n”,Names[j]);
}

Output:
   TejaswiPrasad
    Prasanth
    Anand
Input/output
gets(string) performs input operation .
puts(string)  performs output operation.
Example
#include<string.h>
#include<stdio.h>
main()
{  char numstr[20];
    puts("enter the string");
   gets(numstr);
    puts(numstr);
}   

2D-Array example

/*print Even and Odd no’s among 3x3 matrix/
 #include<stdio.h>
  main( )
{
     int x, i, j, a[i][j], even=0, odd=1;
     for( i=0;i<3; i++ )
      {
          for=0;j<3;j++ )
           {
printf( “enter a no”);
scanf ( “%d”, &a[i][j]);
if( a[i][j]%2== 0 )
          {
             printf( “ even= %d”, a[i][j]  );
            else
               printf( “ odd= %d”,a[i][j] );
             }
 } 

String functions

Read This: strncpy() strncat() strstr () strlen() — Predefined function defined in string.h . — — Returns the len...