Using Library Functions - C Character and String MODULE 25 & 26 C++ STL - Character and String (Template Based)
Using Library Functions - C Character and String MODULE 25 & 26 C++ STL - Character and String (Template Based)
Abilities
Note:
- This Module presented just to show you how to use the functions in C Standard Library. Here, we
have to know which functions are readily available and which header file to be included in our
program as well as how to write the proper syntax.
- The problem encountered by programmers mostly related to data type, the number and order of the
arguments when passing them to the functions and the function return type during the function call.
- The functions used in this Module are from stdio.h, stdlib.h, string.h and ctype.h
headers.
- These functions are used heavily in programming for character and string manipulation such as text and
string search programs, from small programs, binary or linear search up to big and complex search
routines.
- In C++ these routines easily performed by the Standard Template Library (STL).
- Remember that these are not a new constructs, but just normal functions :o). Learn how to use them.
- gcc, g++ and Visual C++ compilation examples are given at the end of this Module.
X.1 Introduction
- In programming, solving the real world problems involved the numbers crunching, these numbers
including characters. Characters are the fundamental building blocks of the program.
- Every program is composed of a sequence of characters interpreted by the computer as a series of
instructions used to accomplish a task.
- A character constant is an int value represented as a character in single quotes.
- This means that the value of a character constant is the integer value of the character in the machine’s
character set.
- For example:
1. Letters.
2. Digit.
3. And various special characters such as +, -, *, /, $ and others.
- Or the set of characters lay on your keyboard. For example, every line of the following address is
strings.
"Mr. Smith"
"39, Big Picture Street"
"Smithsonian, Florida, FL"
www.tenouk.com Page 1 of 25
- Still remember the relation between array and pointers? A string in C/C++ is an array of characters
ending with the null character ('\0') and can be accessed via a pointer to the first character, as you
have learned before.
- In declaring a string, it may be assigned to either,
1. A character array or
2. A variable of type char * (pointer)
- For example:
- When declaring a character array to contain a string, the array must be large enough to store the string
and its terminating NULL character.
- The previous declaration determines the size of the array automatically based on the number of
initializer in the initializer list, which is also its initial value.
- A string can be assigned to an array using scanf. For example:
char word[20];
...
scanf("%s", word);
- The codes will assign a string to character array word[20] or string will be stored in an array word.
- Note that word is an array which is, a pointer, so the & is not needed with argument word. As you
have learned, an array name (without bracket) is a pointer to the first array element.
- Function scanf() will read characters until a space, newline, or end-of-file indicator is encountered.
- The string should be no longer than 19 characters to leave room for the terminating NULL character.
- This library includes several functions that perform useful tests and manipulations of character data.
- Each function receives a character, represented as an int or EOF as an argument.
- Character handling functions manipulate characters as integers.
- Table X.1 summarizes the functions of the character handling library, in ctype.h.
www.tenouk.com Page 2 of 25
Returns a true value if c is printing character other than a
10 int ispunct(int c)
space, a digit, or a letter and 0 otherwise.
Returns a true value if c is a printing character including
11 int isprint(int c)
space (‘ ‘), and 0 otherwise.
Returns a true if c is a printing character other than space
12 int isgraph(int c)
(‘ ‘), and 0 otherwise.
- Let explore the program examples, don’t forget to include ctype.h header file.
//Using functions isdigit(), isalpha(), isalnum(), and isxdigit()
//but using C++ :o), cout…
#include <iostream.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
cout<<"Using functions isdigit(), isalpha(),"<<endl;
cout<<"isalnum(), and isxdigit()"<<endl;
cout<<"-------------------------------------"<<endl;
cout<<"\nAccording to isdigit():"<<endl;
isdigit('8') ? cout<<"8 is a digit\n" : cout<<"8 is not a digit\n";
isdigit('#') ? cout<<"# is a digit\n" : cout<<"# is not a digit\n";
cout<<"\nAccording to isalpha():"<<endl;
isalpha('A') ? cout<<"A is a letter\n" : cout<<"A is not a letter\n";
isalpha('b') ? cout<<"b is a letter\n" : cout<<"b is not a letter\n";
isalpha('&') ? cout<<"& is a letter\n" : cout<<"& is not a letter\n";
isalpha('4') ? cout<<"4 is a letter\n" : cout<<"4 is not a letter\n";
cout<<"\nAccording to isalnum():"<<endl;
isalnum('A') ? cout<<"A is a digit or a letter\n" : cout<<"A is not a digit or a
letter\n";
isalnum('8') ? cout<<"8 is a digit or a letter\n" : cout<<"8 is not a digit or a
letter\n";
isalnum('#') ? cout<<"# is a digit or a letter\n" : cout<<"# is not a digit or a
letter\n";
cout<<"\nAccording to isxdigit():"<<endl;
isxdigit('F') ? cout<<"F is a hexadecimal\n" : cout<<"F is not a hexadecimal\n";
isxdigit('J') ? cout<<"J is a hexadecimal\n" : cout<<"J is not a hexadecimal\n";
isxdigit('7') ? cout<<"7 is a hexadecimal\n" : cout<<"7 is not a hexadecimal\n";
isxdigit('$') ? cout<<"$ is a hexadecimal\n" : cout<<"$ is not a hexadecimal\n";
isxdigit('f') ? cout<<"f is a hexadecimal\n" : cout<<"f is not a hexadecimal\n";
system("pause");
return 0;
}
Output:
www.tenouk.com Page 3 of 25
- Program example #2:
//Using functions islower(), isupper(), tolower(), toupper()
//using C++, cout…
#include <iostream.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
cout<<"\nAccording to islower():"<<endl;
islower('p') ? cout<<"p is a lowercase letter\n" : cout<<"p is not a lowercase
letter\n";
islower('P') ? cout<<"P is a lowercase letter\n" : cout<<"P is not a lowercase
letter\n";
islower('5') ? cout<<"5 is a lowercase letter\n" : cout<<"5 is not a lowercase
letter\n";
islower('!') ? cout<<"! is a lowercase letter\n" : cout<<"! is not a lowercase
letter\n";
cout<<"\nAccording to isupper():"<<endl;
isupper('D') ? cout<<"D is a uppercase letter\n" : cout<<"D is not a uppercase
letter\n";
isupper('d') ? cout<<"d is a uppercase letter\n" : cout<<"d is not a uppercase
letter\n";
isupper('8') ? cout<<"8 is a uppercase letter\n" : cout<<"8 is not a uppercase
letter\n";
isupper('$') ? cout<<"$ is a uppercase letter\n" : cout<<"$ is not a uppercase
letter\n";
cout<<"\nConversion...."<<endl;
cout<<"u converted to uppercase is "<<(char)toupper('u')<<endl;
cout<<"7 converted to uppercase is "<<(char)toupper('7')<<endl;
cout<<"$ converted to uppercase is "<<(char)toupper('$')<<endl;
cout<<"L converted to lowercase is "<<(char)tolower('L')<<endl;
system("pause");
return 0;
}
Output:
www.tenouk.com Page 4 of 25
- Program example #3:
//using functions isspace(), iscntrl(), ispunct(),
//isprint(), isgraph()
#include <iostream.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
cout<<"using functions isspace(), iscntrl(),"<<endl;
cout<<"ispunct(), isprint(), isgraph()"<<endl;
cout<<"-------------------------------------"<<endl;
Output:
www.tenouk.com Page 5 of 25
X.3 String Conversion Functions
- These functions are from the general utilities library, stdlib.h header file.
- They convert strings of digits to integer and floating-point values.
- Table X.2 summarizes the string conversion functions.
- Note the use of const to declare variable nPtr in the function headers (read from right to the left as
nPtr is a pointer to a character constant).
- const declares that the argument values will not be modified during the program execution.
Table X.2: Summary of the string conversion functions of the general utilities library.
int main()
{
double dou;
dou = atof("95.0");
system("pause");
return 0;
}
www.tenouk.com Page 6 of 25
Output:
int main()
{
int i;
i = atoi("1234");
Output:
int main()
{
long newlong;
newlong = atol("123456");
Output:
www.tenouk.com Page 7 of 25
- strtod() – converting string to double with 2 arguments.
int main()
{
double p;
char *thestring = "41.2% sample string";
char *thestringPtr;
p = strtod(thestring, &thestringPtr);
Output:
int main()
{
long x;
char *thestring = "-1234567abc", *remainderPtr;
Output:
www.tenouk.com Page 8 of 25
- strtoul()- converting string to unsigned long with 3 argument program example.
int main()
{
unsigned long x;
char *thestring = "1234567def", *remainderPtr;
Output:
www.tenouk.com Page 9 of 25
int sscanf(char *s, const Equivalent to scanf() except the input is read from the array s
char *format, …) instead of reading from the keyboard.
Table X.3 : The standard input/output library character and string functions
- Program examples functions from the stdio.h, beginning with gets() and putchar().
//function prototype...
void reverse(char *);
int main()
{
//an array for storing the string...
char sentence[80];
Output:
int main()
{
char c, sentence[80];
int i = 0;
www.tenouk.com Page 10 of 25
//while iteration/loop…
while (( c = getchar()) != '\n')
sentence[i++] = c;
//insert NULL at the end of string
sentence[i] = '\0';
puts("\nThe line of text entered was: ");
puts(sentence);
system("pause");
return 0;
}
Output:
- sprintf().
//Using sprintf()
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s[80];
int x;
float y;
printf("Using sprint()\n");
printf("--------------\n");
printf("Enter an integer and a float, separated by space: \n");
scanf("%d%f", &x, &y);
sprintf(s, "Integer:%6d\nFloat:%8.2f", x, y);
printf("\n%s\n%s\n",
"The formatted output stored in array s is: ", s);
system("pause");
return 0;
}
Output:
- sscanf().
//Using sscanf()
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s[] = "31298 87.375";
int x;
float y;
www.tenouk.com Page 11 of 25
printf("Using sscanf()\n");
printf("--------------\n");
sscanf(s, "%d%f", &x, &y);
printf("array, s[] = 31298 87.375\n");
printf("\n%s\n%s%6d\n%s%8.3f\n",
"The values stored in character array s are: ",
"Integer: ", x, "Float: ", y);
system("pause");
return 0;
}
Output:
Table X.4: The string manipulation functions of the string handling library
- Let explore the program examples, beginning with strcpy() and strncpy().
int main()
{
char x[] = "Yo! Happy Birthday to me";
char y[25], z[15];
www.tenouk.com Page 12 of 25
strncpy(z, x, 14);
z[14] = '\0';
Output:
int main()
{
char s1[20] = "Happy ";
char s2[] = "New Year ";
char s3[40] = " ";
Output:
- Let explore the string comparison functions, strcmp() and strncmp(), of the string handling
library. Table X.5 is the summary of the functions and follow by the program examples.
- For these sections, how the computers know that one particular letter comes before another?
- All characters are represented inside the computer as numeric codes, when the computer compares
two strings, it actually compares the numeric codes of the characters in the strings.
- There are three popular coding schemes for character representation:
www.tenouk.com Page 13 of 25
- ASCII, EBCDIC and Unicode are called character codes or character sets.
- String and character manipulations actually involve the manipulation of the appropriate numeric codes
and not the characters themselves.
- These explain the interchangeability of characters and small integers in C/C++.
Table X.5: The string comparison functions of the string handling library
int main()
{
char * s1 = "Happy New Year";
char *s2 = "Happy New Year";
char *s3 = "Happy Birthday";
Output:
- Used to search strings for characters and other strings. Table X.6 is the summary of these functions
and followed by program examples.
www.tenouk.com Page 14 of 25
Function prototype Function description
char *strchr(const char *s, Locates the first occurrence of character c in string s. If c is found, a
int c) pointer to c in s is returned. Otherwise a NULL pointer is returned.
size_t strcspn(const char Determines and returns the length of the initial segment of string s1
*s1, const char *s2) consisting of characters not contained in string s2.
size_t strspn(const char Determines and returns the length of the initial segment of string s1
*s1, const char *s2) consisting only of characters contained in string s2.
Locates the first occurrence in string s1 of any character in string s2.
char *strpbrk(const char
If a character from string s2 is found, a pointer to the character in
*s1, const char *s2)
string s1 is returned. Otherwise a NULL pointer is returned.
char *strrchr(const char Locates the last occurrence of c in string s. If c is found, a pointer to
*s, int c) c in string s is returned. Otherwise is a NULL pointer is returned.
Locates the first occurrence in string s1 of string s2. If the string is
char *strstr(const char
*s1, const char *s2) found, a pointer to the string in s1 is returned. Otherwise a NULL
pointer is returned.
//Using strchr()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *string = "This is a test statement, testing! ";
char character1 = ‘e’, character2 = ‘z’;
Output:
//Using strcspn()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
www.tenouk.com Page 15 of 25
int main()
{
char *string1 = "The value is 3.14159";
char *string2 = "1234567890";
Output:
//Using strpbrk()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *string1 = "This is a test statement";
char *string2 = "search";
//Using strchr()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *string1 = "A zoo has many animals including birds";
int c = ‘m’;
www.tenouk.com Page 16 of 25
printf("\nis: %s\n", strrchr(string1, c));
system("pause");
return 0;
}
Output:
//Using strspn()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *string1 = "The initial value is 3.14159";
char *string2 = "aehilsTuv";
Output:
//Using strstr()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *string1 = "abcdefgabcdefgabcdefg";
char *string2 = "defg";
www.tenouk.com Page 17 of 25
Output:
//Using strtok()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char string[] = "Is this sentence has 6 tokens?";
char *tokenPtr;
Output:
- The functions treat blocks of memory as character arrays and can manipulate any block of data.
- Table X.7 summarizes the memory functions of the string handling library; the term object refers to a
block of data.
www.tenouk.com Page 18 of 25
Function prototype Function description
Copies n characters from the object pointed to by s2 into the
void *memcpy(void *s1, const
void *s2, size_t n) object pointed to by s1. A pointer to the resulting object is
returned.
Copies n characters from the object pointed to by s2 into the
object pointed to by s1. The copy is performed as if the
void *memmove(void *s1,
const void *s2, size_t n) characters are first copied from the object pointed to by s2 into
temporary array, then from the temporary array into the object
pointed to by s1. A pointer to the resulting object is returned.
Compares the first n characters of the objects pointed to by s1 and
int memcmp(const void *s1,
s2. The function return 0, less than 0, or greater than 0 if s1 is
const void *s2, size_t n)
equal to, less than, or greater than s2.
Locates the first occurrence of c (converted to unsigned
void *memchr(const void *s, char) in the first n characters of the object pointed to by s. If c
int c, size_t n) is found, a pointer to c in the object is returned. Otherwise NULL
is returned.
void *memset(void *s, int c, Copies c (converted to unsigned char) into the first n
size_t n) characters of the object pointed to by s. A pointer to the result is
returned.
//Using memcpy()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s1[20], s2[] = "Copying this string into s1";
Output:
//Using memmove()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char x[] = "My home is home sweet home";
www.tenouk.com Page 19 of 25
printf(" Using memmove()\n");
printf(" --------------\n");
printf("The string in array x before memmove() is: \n%s", x);
printf("\nThe string in array x after memmove() using \n");
printf("memmove(x, &x[7], 12) is:\n %s\n", memmove(x, &x[7], 12));
system("pause");
return 0;
}
Output:
//Using memcmp()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s1[] = "ABCDEFGHIJK", s2[] = "ABCDXYZPQR";
printf("Using memcmp()\n");
printf("--------------\n");
printf("s1 = %s\n", s1);
printf("s2 = %s\n", s2);
printf("\nmemcmp(s1, s2, 4) = %2d\n", memcmp(s1, s2, 4));
printf("memcmp(s1, s2, 7) = %2d\n", memcmp(s1, s2, 7));
printf("memcmp(s2, s1, 7) = %2d\n", memcmp(s2, s1, 7));
system("pause");
return 0;
}
Output:
//Using memchr()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *s = "This is a test string";
char p = 'e';
printf("Using memchr()\n");
printf("--------------\n");
printf("char p = \'e\'\n");
printf("s = %s\n", s);
printf("\nThe remainder of string s, after character \'%c\'", p);
www.tenouk.com Page 20 of 25
printf("\nis found, using memchr(s, p, 15)");
printf("\nis \"%s\"\n", memchr(s, p, 15));
system("pause");
return 0;
}
Output:
//Using memset()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char string[40] = "AAAAAAAABBBBBBBBBCCCCCCCCCC";
printf("Using memset()\n");
printf("--------------\n");
printf("string = %s\n", string);
printf("string after memset(string, 'b', 15) =\n%s\n", memset(string, 'b', 15));
system("pause");
return 0;
}
Output:
- The remaining functions of the string handling library are strerror() and strlen().
- Function strerror() takes an error number and creates an error message string. A pointer to the
string is returned.
- Function strlen() takes a string as an argument, and returns the number of characters in a string, the
terminating NULL character is not included in the length.
- The functions are summarizes in table X.8.
Table X.8: The string manipulation functions of the string handling library
- Program example.
www.tenouk.com Page 21 of 25
//Using strerror()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
printf("strerror() - string errors\n");
printf("--------------------------\n");
printf("strerror(1)->%s", strerror(1));
printf("strerror(2)->%s", strerror(2));
printf("strerror(3)->%s", strerror(3));
printf("strerror(4)->%s", strerror(4));
printf("strerror(5)->%s", strerror(5));
printf("strerror(6)->%s", strerror(6));
printf("strerror(7)->%s", strerror(7));
printf("strerror(8)->%s", strerror(8));
printf("strerror(9)->%s", strerror(9));
printf("strerror(9)->%s", strerror(9));
printf("strerror(10)->%s", strerror(10));
system("pause");
return 0;
}
Output:
//Using strchr()
#include <cstdio>
#include <cstring>
int main()
{
char *string1 = "A zoo has many animals including birds";
int c = 'm';
Output:
www.tenouk.com Page 22 of 25
- For C++ character and string manipulations that use the Standard Template Library (STL), please refer
to Module 25 and 26.
- Program examples compiled using g++ (C++) and gcc (C).
//*****ctystring.cpp******
//Using sprintf()
#include <cstdio>
using namespace std;
int main()
{
char s[80];
int x;
float y;
printf("Using sprint()\n");
printf("--------------\n");
printf("Enter an integer and a float, separated by space: \n");
scanf("%d%f", &x, &y);
sprintf(s, "Integer:%6d\nFloat:%8.2f", x, y);
printf("\n%s\n%s\n", "The formatted output stored in array s is: ", s);
return 0;
}
Using sprint()
--------------
Enter an integer and a float, separated by space:
100 33.354
int main()
{
char s1[20], s2[] = "Copying this string into s1";
memcpy(s1, s2, 17);
printf(" Using memcpy()\n");
printf(" --------------\n");
printf("s1[20] = ?\n", s1);
printf("s2[] = %s\n", s2);
printf("\nAfter s2 is copied into s1 with memcpy(),\n");
printf("using memcpy(s1, s2, 17)\n");
printf("\ns1 contains \"%s\"\n", s1);
return 0;
}
Using memcpy()
--------------
s1[20] = ?
s2[] = Copying this string into s1
www.tenouk.com Page 23 of 25
using memcpy(s1, s2, 17)
/*******************cstr.c**************************/
/*Using functions isdigit(), isalpha(), isalnum(), and isxdigit()*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
printf("Using functions isdigit(), isalpha(),\n");
printf("isalnum(), and isxdigit()\n");
printf("-------------------------------------\n");
printf("\nAccording to isdigit():\n");
isdigit('7') ? printf("7 is a digit\n") : printf("7 is not a digit\n");
isdigit('$') ? printf("$ is a digit\n") : printf("$ is not a digit\n");
printf("\nAccording to isalpha():\n");
isalpha('B') ? printf("B is a letter\n") : printf("B is not a letter\n");
isalpha('b') ? printf("b is a letter\n") : printf("b is not a letter\n");
isalpha('&') ? printf("& is a letter\n") : printf("& is not a letter\n");
isalpha('4') ? printf("4 is a letter\n") : printf("4 is not a letter\n");
printf("\nAccording to isalnum():\n");
isalnum('A') ? printf("A is a digit or a letter\n") : printf("A is not a digit or a
letter\n");
isalnum('8') ? printf("8 is a digit or a letter\n") : printf("8 is not a digit or a
letter\n");
isalnum('#') ? printf("# is a digit or a letter\n") : printf("# is not a digit or a
letter\n");
printf("\nAccording to isxdigit():\n");
isxdigit('F') ? printf("F is a hexadecimal\n") : printf("F is not a hexadecimal\n");
isxdigit('J') ? printf("J is a hexadecimal\n") : printf("J is not a hexadecimal\n");
isxdigit('7') ? printf("7 is a hexadecimal\n") : printf("7 is not a hexadecimal\n");
isxdigit('$') ? printf("$ is a hexadecimal\n") : printf("$ is not a hexadecimal\n");
isxdigit('f') ? printf("f is a hexadecimal\n") : printf("f is not a hexadecimal\n");
return 0;
}
According to isdigit():
7 is a digit
$ is not a digit
According to isalpha():
B is a letter
b is a letter
& is not a letter
4 is not a letter
According to isalnum():
A is a digit or a letter
8 is a digit or a letter
# is not a digit or a letter
According to isxdigit():
F is a hexadecimal
J is not a hexadecimal
7 is a hexadecimal
$ is not a hexadecimal
f is a hexadecimal
---------------------------------------------------o0o--------------------------------------------------
www.tenouk.com Page 24 of 25
1. Check the best selling C/C++ books at Amazon.com.
2. Module G (Story) and Module M (Microsoft implementation) for Multibytes, Unicode characters and
Localization.
www.tenouk.com Page 25 of 25