String Handling Library Functions
String Handling Library Functions
library
Outline
• String Conversion Functions
• Character arithmetic
• Sorting of strings.
String Conversion Functions
• String Conversion functions
– In <stdlib.h> (general utilities library)
• Convert strings of digits to integer and
floating-point values
Function prototype Function description
double atof( const char *nPtr ); Converts the string nPtr to double.
int atoi( const char *nPtr ); Converts the string nPtr to int.
long atol( const char *nPtr ); Converts the string nPtr to long int.
double strtod( const char *nPtr, char Converts the string nPtr to double.
**endPtr );
long strtol( const char *nPtr, char Converts the string nPtr to long.
**endPtr, int base );
unsigned long strtoul( const char Converts the string nPtr to unsigned long.
*nPtr, char **endPtr, int base );
atof()
Function atof
• Function atof converts its argument—a string
that represents a floating-point number—to
a double value.
• The function returns the double value.
• If the converted value cannot be represented
—for example, if the first character of the
string is a letter—the behavior of function atof
is undefined.
Example Code
This program
demonstrates
string
conversion
function: atof()
} /* end main */
string1 = abcdefabcdef
string2 = def
}
Decrement
• To display previous char value
void main()
{
char x = ‘b' - 1;
printf("%c", x); // Display Result = ‘a‘
}
Addition
• Adding two ASCII values
void main()
{
char x = 'a‘ + ‘c’;
printf("%c", x); /* Display Result = - ( addition of
ASCII of a and c is 196) */
}
Subtraction
• Adding two ASCII values
void main()
{
char x = ‘z’ – ‘a’;
printf("%c",x); /* Display Result = ↓ (difference
between ASCII of z and a ) */
}
Sorting of strings
• To sort the strings in increasing order.
– That is if list of names is given then sort the list in
alphabetical order.
• Use strcmp() and strcpy() functions.
#include<stdio.h>
#include<conio.h>
#include<string.h>
Program to sort
main()
{ the strings using
char name[20][20];
char temp[20];
int i,j,n,l;
arrays.
printf("Enter the no. of string to be sorted");
scanf("%d",&n);
printf(“Enter %d strings:\n", n);
for(i=0;i<=n;i++)
gets(name[i]);
for(i=0;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
l = strcmp(name[i], name[j]);
if(l>0) // if first string is greater then swap
{
strcpy(temp, name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
puts("Sorted list is:\n");
for(i=0;i<=n;i++)
puts(name[i]);
getch();
}
Enter the no. of string to be sorted 3
Enter 3 strings
lovely
aananya
aman preet
Sorted list is:
aananya
aman preet
lovely