Search This Blog

Thursday, May 31, 2012

String operation in c language

strlen()

The "strlen()" function gives the length of a string, not including the NULL character at the end:
   /* strlen.c */
 
   #include <stdio.h>
   #include <string.h>
 
   void main()
   {
     char *t = "XXX";
     printf( "Length of <%s> is %d.\n", t, strlen( t ));
   }
This prints:
   Length of <XXX> is 3.

 strcpy()

The "strcpy" function copies one string from another. For example:
   /* strcpy.c */
 
   #include <stdio.h>
   #include <string.h>
 
   void main()
   {
     char s1[100],
          s2[100];
     strcpy( s1, "string 1" );
     strcpy( s2, "string 2" );
 
     puts( "Original strings: " );
     puts( "" );
     puts( s1 );
     puts( s2 );
     puts( "" );
 
     strcpy( s2, s1 );
 
     puts( "New strings: " );
     puts( "" );
     puts( s1 );
     puts( s2 );
   }
This will print:
   Original strings:

   string 1
   string 2

   New strings:

   string 1
   string 1
Please be aware of two features of this program:
  • This program assumes that "s1" has enough space to store the final string. The "strcpy()" function won't bother to check, and will give erroneous results if that is not the case.
  • A string constant can be used as the source string instead of a string variable. Using a string constant for the destination, of course, makes no sense.
These comments are applicable to most of the other string functions.

 strncpy()

There is a variant form of "strcpy" named "strncpy" that will copy "n" characters of the source string to the destination string, presuming there are that many characters available in the source string. For example, if the following change is made in the example program:
   strncpy( s2, s1, 5 );
-- then the results change to:
   New strings:

   string 1
   string
Notice that the parameter "n" is declared "size_t", which is defined in "string.h".

 strcat()

The "strcat()" function joins two strings:
   /* strcat.c */
 
   #include <stdio.h>
   #include <string.h>
 
   void main()
   {
     char s1[50],
          s2[50];
     strcpy( s1, "Tweedledee " );
     strcpy( s2, "Tweedledum" );
     strcat( s1, s2 );
     puts( s1 );
   }
This prints:
   Tweedledee Tweedledum

 strncat()

There is a variant version of "strcat()" named "strncat()" that will append "n" characters of the source string to the destination string. If the example above used "strncat()" with a length of 7:
   strncat( s1, s2, 7 );
-- the result would be:
   Tweedledee Tweedle
Again, the length parameter is of type "size_t".

strcmp()

The "strcmp()" function compares two strings:
   /* strcmp.c */
 
   #include <stdio.h>
   #include <string.h>
 
   #define ANSWER "blue"
 
   void main()
   {
     char t[100];
     puts( "What is the secret color?" );
     gets( t );
     while ( strcmp( t, ANSWER ) != 0 )
     {
       puts( "Wrong, try again." );
       gets( t );
     }
     puts( "Right!" );
   }
The "strcmp()" function returns a 0 for a successful comparison, and nonzero otherwise. The comparison is case-sensitive, so answering "BLUE" or "Blue" won't work.
There are three alternate forms for "strcmp()":

 strncmp()

  • A "strncmp()" function which, as might be guessed, compares "n" characters in the source string with the destination string:
 "strncmp( s1, s2, 6 )".

 stricmp()

  • A "stricmp()" function that ignores case in comparisons.

strnicmp()

  • A case-insensitive version of "strncmp" called "strnicmp".

strchr()

The "strchr" function finds the first occurrence of a character in a string. It returns a pointer to the character if it finds it, and null if not. For example:
   /* strchr.c */
 
   #include <stdio.h>
 
   #include <string.h>
 
   void main()
   {
     char *t = "MEAS:VOLT:DC?";
     char *p;
     p = t;
     puts( p );
     while(( p = strchr( p, ':' )) != NULL )
     {
       puts( ++p );
     }
   }
This prints:
   MEAS:VOLT:DC?
   VOLT:DC?
   DC?
The character is defined as a character constant, which C regards as an "int". Notice how the example program increments the pointer before using it ("++p") so that it doesn't point to the ":" but to the character following it.

strrchr()

The "strrchr()" function is almost the same as "strchr()", except that it searches for the last occurrence of the character in the string.

 strstr()

The "strstr()" function is similar to "strchr()" except that it searches for a string, instead of a character. It also returns a pointer:
  char *s = "Black White Brown Blue Green";
  ...
  puts( strstr( s, "Blue" ) );

 strlwr() and strupr()

The "strlwr()" and "strupr()" functions simply perform lowercase or uppercase conversion on the source string. For example:
   /* casecvt.c */
 
   #include <stdio.h>
   #include <string.h>
 
   void main()
   {
     char *t = "Hey Barney hey!";
     puts( strlwr( t ) );
     puts( strupr( t ) );
   }
-- prints:
   hey barney hey!
   HEY BARNEY HEY!

These two functions are only implemented in some compilers and are not part of ANSI C.

introduction to array in c

What is an Array in C Language?

An array in C Programing Language can be defined as number of memory locations, each of which can store the same data type and which can be references through the same variable name.
An array is a collective name given to a group of similar quantities. These similar quantities could be percentage marks of 100 students, number of chairs in home, or salaries of 300 employees or ages of 25 students. Thus an array is a collection of similar elements. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a “string”, where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e we can’t have an array of 10 numbers, of which 5 are ints and 5 are floats.
Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.

Declaration of an Array

Arrays must be declared before they can be used in the program. Standard array declaration is as

type variable_name[lengthofarray];
 
Here type specifies the variable type of the element which is going to be stored in the array. In C programmin language we can declare the array of any basic standard type which C language supports. For example

double height[10];
float width[20];
int min[9];
char name[20];
 
In C Language, arrays starts at position 0. The elements of the array occupy adjacent locations in memory. C Language treats the name of the array as if it were a pointer to the first element This is important in understanding how to do arithmetic with arrays. Any item in the array can be accessed through its index, and it can be accesed any where from with in the program. So
m=height[0];
variable m will have the value of first item of array height.
The program below will declare an array of five integers and print all the elements of the array.

int myArray [5] = {1,2,3,4,5};
/* To print all the elements of the array
for (int i=0;i<5;i++){
   printf("%d", myArray[i]);
}

Initializing Arrays

Initializing of array is very simple in c programming. The initializing values are enclosed within the curly braces in the declaration and placed following an equal sign after the array name. Here is an example which declares and initializes an array of five elements of type int. Array can also be initialized after declaration. Look at the following C code which demonstrate the declaration and  initialization of an array.

int myArray[5] = {1, 2, 3, 4, 5}; //declare and initialize the array in one statement
int studentAge[4];
studentAge[0]=14;
studentAge[1]=13;
studentAge[2]=15;
studentAge[3]=16;

Performing operations on Arrays

Here is a program that will demonstrate the simple operations of the array.

#include <stdio.h>
void oneWay(void);
void anotherWay(void);
int main(void) {
   printf("\noneWay:\n");
   oneWay();
   printf("\nantherWay:\n");
   anotherWay();
}

/*Array initialized with aggregate */
void oneWay(void) {
   int vect[10] = {1,2,3,4,5,6,7,8,9,0};
   int i;
   for (i=0; i<10; i++){
       printf("i = %2d vect[i] = %2d\n", i, vect[i]);
   }
}

/*Array initialized with loop */
void anotherWay(void) {
   int vect[10];
   int i;
   for (i=0; i<10; i++)
        vect[i] = i+1;
   for (i=0; i<10; i++)
        printf("i = %2d vect[i] = %2d\n", i, vect[i]);
}

/* The output of this program is
   oneWay:
   i = 0 vect[i] = 1
   i = 1 vect[i] = 2
   i = 2 vect[i] = 3
   i = 3 vect[i] = 4
   i = 4 vect[i] = 5
   i = 5 vect[i] = 6
   i = 6 vect[i] = 7
   i = 7 vect[i] = 8
   i = 8 vect[i] = 9
   i = 9 vect[i] = 0

   antherWay:
   i = 0 vect[i] = 1
   i = 1 vect[i] = 2
   i = 2 vect[i] = 3
   i = 3 vect[i] = 4
   i = 4 vect[i] = 5
   i = 5 vect[i] = 6
   i = 6 vect[i] = 7
   i = 7 vect[i] = 8
   i = 8 vect[i] = 9
   i = 9 vect[i] = 10
   */
Here is a more complex program that will demonstrate how to read, write and traverse the integer arrays

#include <stdio.h>
void intSwap(int *x, int *y);
int getIntArray(int a[], int nmax, int sentinel);
void printIntArray(int a[], int n);
void reverseIntArray(int a[], int n);

int main(void) {
   int x[10];
   int hmny;

   hmny = getIntArray(x, 10, 0);
   printf("The array was: \n");
   printIntArray(x,hmny);
   reverseIntArray(x,hmny);
   printf("after reverse it is:\n");
   printIntArray(x,hmny);
}

void intSwap(int *x, int *y)
/* It swaps the content of x and y */
{
   int temp = *x;
   *x = *y;
   *y = temp;
}

/* n is the number of elements in the array a.
* These values are printed out, five per line. */
void printIntArray(int a[], int n){
   int i;
   for (i=0; i<n; ){
      printf("\t%d ", a[i++]);
      if (i%5==0)
        printf("\n");
   }
   printf("\n");
}

/* It reads up to nmax integers and stores then in a; sentinel
* terminates input. */
int getIntArray(int a[], int nmax, int sentinel)
{
   int n = 0;
   int temp;

   do {
     printf("Enter integer [%d to terminate] : ", sentinel);
     scanf("%d", &temp);
     if (temp==sentinel) break;
     if (n==nmax)
       printf("array is full\n");
     else
     a[n++] = temp;
   }while (1);
   return n;
}

/* It reverse the order of the first n elements of array */
void reverseIntArray(int a[], int n)
{
   int i;
   for(i=0;i<n/2;i++){
     intSwap(&a[i],&a[n-i-1]);
   }
}

Copy one array into another

There is no such statement in C language which can directly copy an array into another array. So we have to copy each item seperately into another array.

#include <stdio.h>
int main()
{
   int iMarks[4];
   short newMarks[4];
   iMarks[0]=78;
   iMarks[1]=64;
   iMarks[2]=66;
   iMarks[3]=74;
   for(i=0; i<4; i++)
     newMarks[i]=iMarks[i];
   for(j=0; j<4; j++)
     printf("%d\n", newMarks[j]);
   return 0;
}
To summarize, arrays are provides a simple mechanism where more than one elements of same type are to be used. We can maintain, manipulate and store multiple elements of same type in one array variable and access them through index.