C++ String Functions
As you have learned in
chapter 13, strlen, strcat, strcmp are all string functions of C++. Two similar
string functions are the strncat, and strncmp. These work the same as strcat,
and strcmp except they allow more control over how the function operates.
Strncat allow the programmer to specify the number of characters of the source
string that will be appended onto the destination string. It is used as
follows:
strncat(destination,
source, number of characters);
Example:
char FirstName[15] = "John ";
char LastName[15] = "Smith";
strncat(FirstName, LastName, 1);
count << Firstname;
Output:
John S
The strncmp, and
strnicmp allow the comparison of only the first number of specified characters
to be compared. The only difference between the two is strnicmp is not case
sensitive. It is used as follows:
strncmp(string1,
string2, number of characters);
Example:
char FirstName1[15] = "Rob";
char FirstName2[15] = "Robert";
test = strncmp(FirstName, LastName, 3);
cout << test;
Output:
0
Many more string
functions are available in C++. Some of these functions and examples of each
are shown below. You should review your compiler's documentation before using
these functions in order to avoid unexpected results.
_strlwr
Converts all characters to lower case.
_strlwr(string);
_strupr
Converts all characters to upper case.
_strupr(string);
strrev
Reverses the string.
strrev(string);
strchr
Locates the first occurrence of a character in a string.
CharPointer = strchr(string, 'char');
strrchr
Locates the last occurrence of a character in a string.
CharPointer = strrchr(string, 'char');
strspn
Returns the number of matches found in the string.
Count = strspn(string, 'char');
strpbrk
Returns a character pointer to the first occurrence of characters
in a string. It will return the pointer of which ever character comes first.
CharPointer = strpbrk(string, "chars")
strstr
Returns a character pointer to the first occurrence of a string in
a string.
CharPointer = strstr(string, "string");
Comments
Post a Comment