Frequently used header files ( string.h , algorithm ) in C/C++

I am starting this briefing assuming that the reader is already known about the basic structure of programming with C. Here you will find a brief collection which are used frequently in programming.

Let’s start from #include
strlen(): int strlen(consts char *array)
A frequently used function and quite familiar to everyone is strlen() which returns the length of a character array passed to the function.

Example:

char arr[]=”This is a strlen function test. ”;
Printf(“%d”,strlen(arr));
Output:  30


strcmp(): int strcmp(const char *a,const char *b)

This one is used for comparing two strings. It can be used on Big number comparison also.
Exapmle:


	char  a[]=”ABC”;
	char  b[]=”ABC”;
	char  c[]=”AAA”;
	// now 
	int  x= strcmp(a,b)  ; // x= 0  as a==b
	x= strcmp(a,c);	// x>0  as a>c;  1st  parameter>  2nd parameter
	x= strcmp(c,a)        // x<0  as c<a;   1st  parameter<  2nd parameter

Now what is the basis of comparison of this function and what does this comparison actually mean? This comparison actually means lexicographically comparison.
Each of the character has a ASCII value . and ASCII value thus ‘A’ is less than ‘a’
So if we compare them ‘a’ >’A’

Now let’s have a practice about this type of comparison .
1. strcmp( “abc”,”Abc” ) Output : >0
2. strcmp(“cow”,”woc”) Output: 0
4. strcmp(“cow”,”cowa”) Output: <0
Now have a look closely
A[]= “cow”
B[]= ”cowa”
If we see the memory we would see like this :

A[] :‘c’ ‘o’ ‘w’ 0 0
B[] :‘c’ ‘o’ ‘w’ ‘a’ 0

Now see place 0 : A[0]==B[0] // ‘c’
A[1]==B[1] // ‘o’
A[2]==B[2] // ‘c’
A[3]<B[3] // 0<’a’ by ascii value ( here 0 ,not ‘0’)
So,now strcmp return a value less than 0.
Thus strcmp(A,B)’y’ so it returns >0 value.
It will return 0 if and only if two strings are equal.

strcpy(): char *strcpy(char *destination,const char *source)
This function is used to copy 2nd string to 1st string.
Example:

char destination[]=”DEPT”;
char source[]=”CSE”;
strcpy(destination,source);

destination: “CSE”
source : ”CSE”
One thing is very important and should be remembered that Array size of destination must be greater than array of source, Else program may crash.
Now the question is why?
Look closely at the memory.
Say,
char dest=”cse”; // size is 4 considering the NULL
char source=”department”; // size is 11 considering the NULL
strcpy(dest,source);
Is it possible ?

dest: memory size 4 (considering the NULL)
‘c’ ‘s’ ‘e’ 0

Source : memory size 11 (considering the NULL)
‘d’ ‘e’ ‘p’ ‘a’ ‘r’ ‘t’ ‘m’ ‘e’ ‘n’ ‘t’ 0

Now think is it possible to keep this 11 elements including NULL (0) in 4 sized array of “dest” ? so you have to ensure that the destination will be long enough so that no overflow occurs .

strcat(): char * strcat(char *a,const char *n)
This function is generally used for concatenation. If two strings are str1,str2 then,

char str1[100],str2[100];
gets(str1);  // say input is “cse” 
gets(str2);   // say input is “ rocks.”
strcat(str1,str2);
puts(str1);    // output : cse rocks.
puts(str2);    // output : rocks

1st string is changed and no change to 2nd one .
But here we also have to be careful about size of 1st parameter . As 2nd parameter is added to 1st one , size should be available otherwise overflow will occur.

memset() : void * memset ( void * ptr, int value, size_t num )
This function is very much helpful.If you want to initialize an array with a desired value then what you will do, just iterate.but memset support this with a single statement.

Lets see

  int a[100];  // or  char a[100]
    for(int i=0;i<50;i++) 
 	a[i]= ‘f’;

this may be done by also this:

memset(a,’f’,50*sizeof(a[0]) );

if any one want to insert whole array a single value than

memset(a,’f’,sizeof(a));

A complete c code is also provided here for clarification. 

#include 
#include 

int main ()
{
  char str[] = "almost every programmer should know memset!";
  memset (str,'-',6);
  puts (str);
  return 0;
}

strtok: char * strtok ( char * str, const char * delimiters )
strtok is a superb function indeed. According to me this function is more valuable than any other cstring’s functions. Now let’s see ,what is it ?

char str[]=”I am a cse student. Oh! Shit, I forgot to say my high CGPA.”
strtok= string tokenizer (:P)

If you want to tokenize a string by space ,’!’ ,’.’, ‘,’ or any characters then you can do it by strtok. Now what does tokenize means ? sometimes we take input of an array of a paragraph and we need to separate the words form it. In this case words are our token .
You can use strtok in this case.
char * p =strtok(str,” .,!.”);
now we are ready to get tokens :
1. I
2. am
3. a
4. cse
5. student
6. Oh
7. shit
8. I
9. forgot
10. to
11. say
12. my
13. High
14. CGPA
We have 14 tokens as we has given delimiters ” .,!.”
Here a c code is also provided for more clarification.

#include 
#include 

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string %s into tokens\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

Output:
Splitting string "- This, a sample string." into tokens:
This
a
sample
string

This were frequently used string manupulating functions.

In c++ there is anothet header file algorithm.h which provides us many bullt-in function Which are frequently used by us. Here I am giving an example for describing some of them.

#include 
#include 
using namespace std;

int main()
{
    int a=10,b=15;

//a=10 b=15
    swap(a,b);
//a=15 b=10

    cout<< max(a,b)<

There are many of these types of usuful functions in this header file.For further information see books.

There is another thing called STL which means Standard Template Library,another useful library of functions which makes programmer's job easier. This function provides with decrease of line of codes.

Frequently used container classes of STL :
1. vector
2. queue
3. string
4. stack
5. map
6. list
7. set
8. pair

Fore more about STL click here

Thanking for reading this,
Ujjal Suttra Dhar
sssujjal@gmail.com

One Reply to “Frequently used header files ( string.h , algorithm ) in C/C++”

Leave a Reply

Your email address will not be published. Required fields are marked *