Strings |
|
To display these characters as a group, you can use the following:
Here is such a program:
This would produce:
When studying arrays, we were listing the numeric members of the array between curly bracket. Here is an example: int Number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; Because a character is initialized by including it in single-quotes, when creating an array of characters, to initialize it, you must also include each letter accordingly. A name such as James can be initialized as follows: char Name[6] = { 'J', 'a', 'm', 'e', 's' }; As done with other arrays, each member of this array of characters can be accessed using its index. Here is an example: #include <iostream> using namespace std; int main() { char Name[6] = { 'J', 'a', 'm', 'e', 's' }; cout << "The name is " << Name[0] << Name[1] << Name[2] << Name[3] << Name[4]; return 0; } The C/C++ provides another alternative. It allows you to declare and initialize the array as a whole. To do this, include the name in double-quotes. With this technique, the curly brackets that delimit an array are not necessary anymore. Here is an example: char Name[12] = "James"; With this technique, the item between the double-quotes is called a string. It is also referred to as the value of the string or the value of the variable. When declaring and initializing an array of characters, the compiler does not need to know the number of characters of the string. In fact, you can let the compiler figure it out. Therefore, you can leave the square brackets empty: char Name[] = "James"; After declaring such an array, the compiler would count the number of characters of the variable, add one more variable to it and allocate enough space for the variable. The character added is called the null-terminated character and it is represented as \0. Therefore, a string such as James would be stored as follows:
This something you will need to remember regularly.
Like any other variable, before using a string, you must first declare it, which is done by type the char keyword, followed by the name of the variable, followed by square brackets. When declaring the variable, if/since you do not know the number of characters needed for the string, you must still provide an estimate number. You can provide a value large enough to accommodate the maximum number of characters that would be necessary for the variable. For a person's name, this could be 20. For the title of a book or a web page, this could be longer. Here are examples: char Name[20]; char BookTitle[40]; char WebReference[80]; char WeekDay[4]; To request the value of an array of characters, use the cin extractor just like you would proceed with any other variable, without the square bracket. Here is an example: char WeekDay[12]; cout << "Enter today's name: "; cin >> WeekDay; To display the value of an array of characters, use the cout extractor as we have used it with all other variables, without the square brackets. Here is an example:
Here is an example of running the program:
C/C++ treats arrays of characters differently than it does the other arrays. For example, we have learned to declare a two-dimensional array of integers as follows:
This variable is in fact two arrays and each array contains 6 integers. For a string, if you want to declare a two-dimension array of characters, the first dimension specifies the number of string in the variable. The second dimension specifies the number of characters that each string can hold. Here is an example: char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" }; In this case, the StudentName variable is an array of 4 strings and each string can have a maximum of 9 characters (+1 for the null-terminated character). To locate a string on this variable, type the name of the array followed by its index, which is the index of the column. This means that the first string of the StudentName array can be accessed with StudentName[0]. The second would be StudentName[1], etc. This allows you to display each string on the cout extractor:
This would produce: Student Names Student 1: Hermine Student 2: Paul Student 3: Gertrude Student 4: Leon When declaring and initializing such an array, the compiler does not need to know the number of strings in the array; it can figure it out on its own. Therefore, you can leave the first pair square brackets empty. If you are only declaring the array but cannot initialize, then you must specify both dimensions. To request the values of the array, once again, locate each member using its index. Here is an example:
There are two alternatives to solve this problem: you can use the getline() function from the basic_string library or you can use the gets() function from the C language.
Earlier, we declared an array as follows: char EndMe[] = ""; The name of the variable is a pointer to the beginning of the array. For this reason, the name of the reason is sufficient to locate its value. Since in this case we do not specify the number of characters in the array, we can also just use a pointer to the array as the beginning of the array. The array can therefore be declared as follows: char *EndMe = ""; Once again, to display the value of such an array, simply call its name on the cout extractor: #include <iostream> using namespace std; int main() { char *EndMe = ""; cout << EndMe; return 0; } To request the value of an array of characters from the user, you can declare a pointer to char and initialize it with an estimate number of characters using the new operator. Here is an example: #include <iostream> using namespace std; int main() { char *StudentName = new char[20]; cout << "Enter Sudent First Name: "; cin >> StudentName; cout << "\nStudent First Name: " << StudentName; return 0; } Here is an example of running the program: Enter Sudent First Name: Charlotte Student First Name: Charlotte |
|
Declaring and Initializing an Array of Characters |
From our study and use of characters, we have seen that, to declare a character variable, we can use any C++ valid name. To initialize a character variable, type it between single-quotes. Here is an example: char Answer = ‘y’; To declare an array of characters, type the char keyword followed by the techniques we used to declare the other arrays. The syntax is: char ArrayName[Dimension]; The char keyword lets the compiler know that you are declaring a variable of character type. The square brackets let the compiler know that you are declaring an array. The name of the array follows the same rules and suggestions we have used for the other variables. Once again, the dimension of the array could be an approximation of the number of characters you anticipate. To initialize an array of characters, you use the curly brackets. Each character must be enclosed in single-quotes. If you know the characters you will be using to initialize the array, you should omit specifying the dimension. Here is an example: char Color[] = { 'B', 'l', 'a', 'c', 'k' }; Another technique used to initialize an array of characters is to type the group of characters between double-quotes. Since you know the array, let the compiler figure out its dimension. Here is an example: char Country[] = "Swaziland"; Any of these two techniques would allow you to display the string using the cout operator. The compiler already knows the dimension and the contents of the array: |
#include <iostream> using namespace std; int main() { char Color[] = { 'B', 'l', 'a', 'c', 'k' }; char Country[] = "Swaziland"; cout << "Color = " << Color << endl; cout << "Country = " << Country; return 0; }
This would produce:
Color = Black Country = Swaziland
Requesting an Array of Characters |
Instead of initializing an array, sometimes you will have to wait until the program is running, to assign a value to the array. First, you must declare the array, specifying an approximate dimension. To request the value of an array of characters, use the cin operator, specifying only the name of the array. Here is an example: |
#include <iostream> using namespace std; int main() { char FirstName[20]; char MI; char LastName[20]; cout << "The following pieces of information are need" << "to complete your application\n"; cout << "First Name: "; cin >> FirstName; cout << "Middle Initial: "; cin >> MI; cout << "Last Name: "; cin >> LastName; cout << "\nMember Information"; cout << "\nFull Name: " << FirstName << " " << MI << ". " << LastName; return 0; }
Here is an example of running the program:
The following pieces of information are need to complete your application First Name: Michael Middle Initial: J Last Name: Callhoun Member Information Full Name: Michael J. Callhoun
If you use the “normal” cin operator above, the compiler expects the user to type a one-word string from the keyboard. If you want the user to type text that includes space, you should use the cin::getline() function. The syntax of the getline() function is: cin.getline(ArrayName, Dimension, Delimiter=’\n’); The array name is the one you used when declaring the array. The dimension is the same value you set when declaring the variable. The delimiter is an optional character that the user would type to specify the end of the string. By default, the compiler expects the user to press Enter to end the string. Logically, the following program illustrates the use of the cin::getline() function to request text strings from the user: |
#include <iostream> using namespace std; int main() { char Author[40]; char Title[40]; char Publisher[50]; cout << "Book Collection\n"; cout << "Author: "; cin.getline(Author, 40); cout << "Title: "; cin.getline(Title, 40); cout << "Publisher: "; cin.getline(Publisher, 50); cout << "\nBook Information"; cout << "\nAuthor Name: " << Author << "\nBook Title: " << Title << "\nPublisher: " << Publisher; return 0; }
Here is an example of running the program:
Book Collection Author: Elliot Mendelson Title: 3000 Solved Problems In Calculus Publisher: McGraw Hill Book Information Author Name: Elliot Mendelson Book Title: 3000 Solved Problems In Calculus Publisher: McGraw Hill
Arrays of Characters and Pointers |
|
Declaration of an Array of Characters |
We have learned to declare an array of characters using the square brackets and to initialize it using the assignment operator. By not specifying the dimension of the array, we are relying on the compiler to find out how many items the array has. Here is an example: |
#include <iostream> using namespace std; int main() { char Country[] = "Republique d'Afrique du Sud"; cout << "Country Name: " << Country << "\n\n"; return 0; }
As you can see for this example, to display the value of the Country variable, although it is an array, all the compiler needs is the name. How come? As it happens, when you create an array of characters, such as the Country variable above, the name of the array is the same as Country[0]. In other words, it represents the beginning of the space memory occupied by the variable. As we saw when studying pointers, this beginning of the space occupied by a variable is referred to as its address. Because the compiler knows this and is able to figure it out, C++ provides another solution. Instead of declaring the array with empty square brackets, since we are in fact referring to the address of the variable, we can declare it a pointer to char. Therefore, the above program can be written as follows: |
#include <iostream> using namespace std; int main() { char *Country = "Republique d'Afrique du Sud"; cout << "Country Name: " << Country << "\n\n"; return 0; }
Both programs would produce the same result. There is something important to know about this new version. The asterisk on the name informs the compiler that it should consider the Country variable starting at its address and up. If you do not initialize the variable, the compiler would not complain as long it is now able to locate the variable. Based on this, you can initialize the variable when you are ready and not necessarily when you declare it. Keep in mind that this theory is valid only for an array of characters; for example the following program will not compile: |
#include <iostream> using namespace std; int main() { double *Value; Value = 12.55; cout << "Value = " << Value; return 0; }
On the other hand, the following declaring of an array of characters and its later initialization is perfectly legal: |
#include <iostream> using namespace std; int main() { char *Country; Country = "Republique d'Afrique du Sud"; cout << "Country Name: " << Country << "\n\n"; return 0; }
Dynamic Arrays of Characters |
A dynamic object is one whose memory is requested and used only when needed. Such objects are created using the new operator. In the same way, to dynamically create an array, you use the new operator. To do this, the variable must be declared a pointer to char, as done above. Then assign the new char expression that followed by a pair of square brackets. In the square brackets, specify the desired dimension of the array. An example would be: char *Country = new char[20]; After declaring such a variable, you can assign it any value you want. Here is an example: |
#include <iostream> using namespace std; int main() { char *Country = new char[20]; Country = "Equatorial Guinea"; cout << "Country Name: " << Country; cout << "\n\n"; return 0; }
Passing an Array of Characters |
Like other regular arrays, you can pass an array of characters to a function or you can return an array of characters from a function. To pass an array of characters to a function, when declaring and when defining the function, provide the name of the array followed by empty parentheses. When calling the function, provide only the name of the argument you are passing. Here is an example: |
#include <iostream> using namespace std; void ShowCountry(const char S[]) { cout << "Country Name: " << S << "\n\n"; } int main() { char Country[] = "Republique d'Afrique du Sud"; ShowCountry(Country); return 0; }
Alternatively, as we have learned that you can also declare an array of characters using a pointer to char, when declaring and when defining the array, you can provide the argument as a pointer to char. When calling the function, provide the argument of the function by specifying only the name of the argument: |
#include <iostream> using namespace std; void ShowCountry(const char *S) { cout << "Country Name: " << S << "\n\n"; } int main() { char *Country = "Republique d'Afrique du Sud"; ShowCountry(Country); return 0; }
Returning an array of Characters |
Just as you can pass an array of characters to a function, you can also return such an array from a function. To do this, the function must be declared and defined as a pointer to char. Here is an example: char *GetFirstName(); When calling such a function, you are requesting its value and want to assign it to a variable, make sure that the variable is also declared as pointer to char. Here is an example: |
#include <iostream> using namespace std; char *GetFirstName() { char *FName = new char[20]; cout << "Enter First Name: "; gets(FName); return FName; } int main() { char *FirstName; FirstName = GetFirstName(); cout << "First Name: " << FirstName << "\n\n"; return 0; }
Multidimensional Arrays of Characters |
|
Double-Dimensional Arrays Declaration |
Once again, an array of characters is different from an array of other regular data types. Imagine you want to create various lists of countries. You would declare such an array as follows: char Country[3][8]; Unlike other data types, it is important to know what each dimension represents. This array initiates 3 lists of countries. Each country can have up to 8 letters. In other words, the first dimension represents the number of items that make up the list. It is as if you had declared an array of flowing-point numbers as double Distance[5] which represents a series of 5 distances. The second dimension of an array of characters represents the maximum number of characters that each item can have. To initialize a 2-dimensional array, assign an opening and a closing curly brackets to it. Inside of the curly brackets, provide each item between double-quotes. Here is an example: |
#include <iostream> using namespace std; int main() { char Country[3][20] = { "Afrique du Sud", "Australie", "Zimbabwe" }; return 0; }
Make sure that the number of items of your list is equal to or less than the first dimension. If this condition is not met, the compiler would display an error. For example, the following program will not compile because the declaration of the array specifies that the array is made of three items but is initialized with 6: |
#include <iostream> using namespace std; int main() { char Country[3][20] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" }; return 0; }
In the same way, make sure that each item of the array has a number of characters (or letters) that is equal to or less than the second dimension. The following program will not compile because two items of the array (the 1st and the last) have more than 10 letters after you had declared that the maximum number of letters of each item of the arrays would be 10 characters: |
#include <iostream> using namespace std; int main() { char Country[6][10] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" }; return 0; }
To access an item of the 2-dimensional array of characters, provide its name followed by its index. The index here is from the first dimension because the first dimension specifies the number of items of the array. For example, you can access the 3rd item of the above Country array with Country[4]. The compiler does not need the dimension of each item to display it. Here is an example: |
#include <iostream> using namespace std; int main() { char Country[6][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" }; cout << "Countries Names"; cout << "\nCountry 1: " << Country[0]; cout << "\nCountry 2: " << Country[1]; cout << "\nCountry 3: " << Country[2]; cout << "\nCountry 4: " << Country[3]; cout << "\nCountry 5: " << Country[4]; cout << "\nCountry 6: " << Country[5]; cout << "\n\n"; return 0; }
This would produce:
Countries Names Country 1: Afrique du Sud Country 2: Australia Country 3: Zimbabwe Country 4: Sri Lanka Country 5: Yemen Country 6: El Salvador
In the same way, you can use a for loop to scan the array, accessing each member by its position. Here is an example: |
#include <iostream> using namespace std; int main() { char Country[6][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" }; cout << "Countries Names"; for(int i = 0; i < 6; ++i) cout << "\nCountry " << i + 1 << ": " << Country[i]; cout << "\n\n"; return 0; }
When you declare a two-dimensional array, yo do not have to know how many items the array is made of but you must know the maximum number of characters that each item can be mad of. This property of arrays can be used to leave the first square brackets empty: |
#include <iostream> using namespace std; int main() { char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" }; cout << "Countries Names"; for(int i = 0; i < 6; ++i) cout << "\nCountry " << i + 1 << ": " << Country[i]; cout << "\n\n"; return 0; }
We saw earlier that, using a pointer to char, you do not have to specify the number of characters that composes an array. For a 2-dimensional array, you can let the compiler figure out how many items the array uses. To do this, when declaring the array, precede the name of the array with an asterisk. This will allow the compiler to locate the address of the first item and take over from there. Based on this, the above array can be declared as follows: |
char *Country[15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };
We also saw earlier that the name of an represents the address of the variable. In the same way, you do not have to find the item that has the highest number of characters and specify it as the second dimension of the array. You can let the compiler figure out this by letting the square brackets empty. By your initializing the array, the compiler would figure out how much space each item needs. Therefore, the above array can be declared as follows: |
#include <iostream> using namespace std; int main() { char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" }; cout << "Countries Names"; for(int i = 0; i < 6; ++i) cout << "\nCountry " << i + 1 << ": " << Country[i]; cout << "\n\n"; return 0; }
Two-Dimensional Arrays of Characters and Functions |
When declaring and when defining a function that takes as argument a 2-dimensional array, the argument is passed with two pairs of square brackets. The first square bracket should be left empty although you are allowed to specify its dimension. This first pair of square brackets lets the compiler know the argument represents a group of strings. The second pair of square brackets must have the maximum characters that each item of the array has. Such a function can be declared and defined as follows: void ShowCountries(char S[][15]); When calling such a function, provide only the name of the array. The compiler can figure out the rest by referring to the definition of the function (of course, this is still your responsibility). Here is an example: |
#include <iostream> using namespace std; void ShowCountries(char S[][15]) { cout << "Countries Names"; for(int i = 0; i < 3; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; } int main() { char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" }; ShowCountries(Country); cout << "\n\n"; return 0; }
If you expect the function to also process the (whole) array, you can pass a second argument that would hold the actual number of items that composes the array passed as argument. Here is an example: |
#include <iostream> using namespace std; void ShowCountries(char S[][15], const int n) { cout << "Countries Names"; for(int i = 0; i < n; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; } int main() { char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" }; ShowCountries(Country, 6); cout << "\n\n"; return 0; }
You can also pass the argument as a pointer to char after declaring the array as such. This, of course, allows the compiler to better manage memory because it can figure out how many items are in the array and how much space each item needs. To pass an array as a pointer to char, when declaring and when defining the function, precede the name of the argument with an asterisk and type an empty pair of square brackets on the right side of the name of the argument. You can call this function the same way we did above: |
#include <iostream> using namespace std; void ShowCountries(char *S[], const int n) { cout << "Countries Names"; for(int i = 0; i < n; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; } int main() { char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" }; ShowCountries(Country, 6); cout << "\n\n"; return 0; }
Alternatively, when declaring and when defining the function, you can specify that the argument is a pointer to char: |
#include <iostream> using namespace std; void ShowCountries(char **S, const int n) { cout << "Countries Names"; for(int i = 0; i < n; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; } int main() { char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" }; ShowCountries(Country, 6); cout << "\n\n"; return 0; }
Introduction to Strings |
|
Defining a String |
A string is an array of characters whose last character is \0. A typical string, such as Pacifique, is graphically represented as follows: |
P | a | c | i | f | i | q | u | e | \0 |
The last character \0 is called the null-terminating character. For this reason, a string is said to be null-terminated. The string library ships with a lot of functions used to perform almost any type of operation on almost any kind of string. Used under different circumstances, the string functions also have different syntaxes. The strings that you can use in your program may be defined in various libraries depending on your compiler but most of the time, they are available once you include the string library that is defined in the std namespace. For example, the functions we are about to review are part of the C language. The strings that are part of the (C++) Standard Template Library (STL) are defined in the string class of the std namespace. Based on this, most compilers make all these functions accessible once you include the string library and the std namespace in your program. |
String Manipulation Functions |
The C++ and its parent the C languages do not have a string data type. In C and C++, strings are created from arrays. Therefore, the C++ language relies on operations performed on the arrays of characters or pointers to char. The functions used for this purpose are numerous and you should know what they are used for. As a reminder, thanks to the features of arrays of characters and the friendship between arrays of characters and strings, there are two main ways you can declare and initialize a string: char *Thing = “Telephone”; char Major[] = “Computer Sciences”; |
The Length of a String |
In many operations, you will want to know how many characters a string consists of. To find the number of characters of a string, use the strlen() function. Its syntax is: int strlen(const char* Value); The strlen() function takes one argument, which is the string you are considering. The function returns the number of characters of the string. Here is an example: |
#include <iostream> using namespace std; int main() { char *School = "Manchester United"; int Length = strlen(School); cout << "The length of \"" << School << "\" is " << Length << " characters\n\n"; return 0; }
This would produce:
The length of "Manchester United" is 17 characters
The strcat() Function |
If you have two strings, to append one to another, use the strcat() function. Its syntax is: char *strcat(char *Destination, const char *Source); The strcat() function takes two arguments. The second argument, called the source string, is the string you want to add to the first string; this first string is referred to as the destination. Although the function takes two arguments. It really ends up changing the destination string by appending the second string at the end of the first string. This could be used to add two strings. Here is an example: |
#include <iostream> using namespace std; int main() { char *Make = "Ford "; char *Model = "Explorer"; cout << "Originally, Make = " << Make; strcat(Make, Model); cout << "\n\nAfter concatenating, Make = " << Make << endl; return 0; }
This would produce:
Originally, Make = Ford After concatenating, Make = Ford Explorer
The strncat() Function |
Like the strcat() function, the strncat() function is used to append one string to another. The difference is that, while the strcat() considers all characters of the source string, the strncat() function allows you to specify the number of characters from the source string that you want to append to the destination string. This means that, if the source string has 12 characters, you can decide to append only a set number of its characters. The syntax is: char* strncat(char* Destination, const char* Source, int Number); Besides the same arguments as the strcat() function, the Number argument sets the number of characters considered from Source. To perform the concatenation, the compiler would count characters from left to right on the source string. Here is an example: |
#include <iostream> using namespace std; int main() { char *Make = "Ford "; char *Model = "Explorer"; cout << "Originally, Make = " << Make; strncat(Make, Model, 3); cout << "\n\nAfter concatenating, Make = " << Make; return 0; }
This would produce:
Originally, Make = Ford After concatenating, Make = Ford Exp
Copying One String Into Another |
The strcpy() function is used to copy one string into another string. In English, it is used to replace one string with another. The syntax of the strcpy() function is: char* strcpy(char* Destination, const char* Source); This function takes two arguments. The first argument is the string that you are trying to replace. The second argument is the new string that you want to replace. There are two main scenarios suitable for the strcpy() function: To replace an existing string or to initialize a string. The following would initialize a string: |
char CarName[20]; strcpy(CarName, "Toyota Camry"); cout << "Car Name: " << CarName;
If you have two strings and copy one into another, both strings would hold the same value: |
#include <iostream> using namespace std; int main() { char carName1[] = "Ford Escort"; char carName2[] = "Toyota 4-Runner"; cout << "The String Copy Operation"; cout << "\nFirst Car: " << carName1; cout << "\nSecond Car: " << carName2; strcpy(carName2, carName1); cout << "\n\nAfter using strcpy()..."; cout << "\nFirst Car: " << carName1; cout << "\nSecond Car: " << carName2 << endl; return 0; }
This would produce:
The String Copy Operation First Car: Ford Escort Second Car: Toyota 4-Runner After using strcpy()... First Car: Ford Escort Second Car: Ford Escort
The strncpy() Function |
The strncpy() function works like the strcpy() function. As a difference, the strncpy() function allows you to specify the number of characters that the compiler would copy from the source string. Here is the syntax: char* strncpy(char* Destination, const char* Source, int Number); The Number argument specifies the number of characters that will be copied from the Source string. Here is an example: |
#include <iostream> using namespace std; int main() { char CarName1[] = "Ford Escort"; char CarName2[] = "Toyota 4-Runner"; cout << "The String Copy Operation"; cout << "\nFirst Car: " << CarName1; cout << "\nSecond Car: " << CarName2; strncpy(CarName2, CarName1, 8); cout << "\n\nAfter using strncpy() for 8 characters"; cout << "\nFirst Car: " << CarName1; cout << "\nSecond Car: " << CarName2 << endl; return 0; }
This would produce:
The String Copy Operation First Car: Ford Escort Second Car: Toyota 4-Runner After using strncpy() for 8 characters First Car: Ford Escort Second Car: Ford Esc-Runner
The strdup() Function |
The strdup() function is used to make a copy of create a duplicate of that string. Its syntax is: char* strdup(const char *S); This function takes as an argument the string you want to duplication and returns the duplicated string. |
#include <iostream> using namespace std; int main() { char *FirstName1 = "Charles"; char *FirstName2 = "Andy"; char *LastName1 = "Stanley"; char *LastName2; LastName2 = strdup(LastName1); cout << "Father: " << FirstName1 << ' ' << LastName1 << endl; cout << "Son: " << FirstName2 << ' ' << LastName2; return 0; }
This would produce:
Father: Charles Stanley Son: Andy Stanley
Comparing Strings |
|
Various routines are available for strings comparison. The C-String library is equipped with functions that perform the comparisons by characters. Alternatively, some compilers like Borland C++ Buider ships with additional multiple functions to perform these comparisons on null-terminated strings. |
The strcmp() Function |
The strcmp() function compares two strings and returns an integer as a result of its comparison. Its syntax is:
int strcmp(const char* S1, const char* S2);
This function takes two strings, S1 and S2 and compares them. It returns
#include <iostream> using namespace std; int main() { char *FirstName1 = "Andy"; char *FirstName2 = "Charles"; char *LastName1 = "Stanley"; char *LastName2 = "Stanley"; int Value1 = strcmp(FirstName1, FirstName2); int Value2 = strcmp(FirstName2, FirstName1); int Value3 = strcmp(LastName1, LastName2); cout << "The result of comparing " << FirstName1 << " and " << FirstName2 << " is\t" << Value1 << endl; cout << "The result of comparing " << FirstName2 << " and " << FirstName1 << " is\t" << Value2 << endl; cout << "The result of comparing " << LastName1 << " and " << LastName2 << " is\t" << Value3; return 0; }
This would produce:
The result of comparing Andy and Charles is -2 The result of comparing Charles and Andy is 2 The result of comparing Stanley and Stanley is 0
The strncmp() Function |
The strncmp() function compares two strings using a specified number of characters and returns an integer as a result of its findings. Its syntax is: int strncmp(const char* S1, const char* S2, int Number); This function takes three arguments. The first two arguments are the strings that need to be compared. The 3rd argument specifies the number of characters considered for the comparison. It returns
|
The stricmp() Function |
The stricmp() function compares two strings without regard to their case. In other words, this function does not take into consideration if there is a mix of uppercase and lowercase characters in the strings. The syntax of the function is: int stricmp(const char* S1, const char* S2); This function takes two strings, S1 and S2 and compares them. It returns
|
The strnicmp() Function |
The strnicmp() function compares two strings without regard to their case but considers only a specified number of characters. The syntax of the function is: int strnicmp(const char* S1, const char* S2, int n); This function takes two strings, S1 and S2 and compares them. It returns
|
Working With Individual Characters |
|
The strchr() Function |
The strchr() function looks for the first occurrence of a certain character in a string. Its syntax is: char* strchr(const char* S, char c); This function takes two arguments. The second argument specifies what character to look for in the first argument which is a string. If the character c appears in the string S, the function would return a new string whose value starts at the first occurrence of c in S. If the character c does not appear in the string S, then the function would return NULL. |
The strrchr() Function |
The strrchr() function examines a string starting at the end (right side) of the string and looks for the first occurrence of a certain character. Its syntax is: char* strrchr(const char* S, char c); The first argument is the string that needs to be examined. The function will scan the string S from right to left. Once it finds the first appearance of the character c in the string, it would return a new string whose value starts at that first occurrence. If the character c does not appear in the string S, then the function would return NULL. |
Working With Sub-Strings |
|
The strstr() Function |
The strstr() function looks for the first occurrence of a sub-string in another string and returns a new string as the remaining string. Its syntax is: |
char* strstr(const char* Main, const char *Sub);
The first argument of the function is the main string that would be examined. The function would look for the second argument, the Sub string appearance in the main string. If the Sub string is part of the Main string, then the function would return a string whose value starts at the first appearance of Sub and make it a new string. If Sub is not part of the Main string, the function would return a NULL value. |
Working With Character Cases |
|
The strlwr() Function |
The strlwr() function is used to convert a string to lowercase. Its syntax is: |
char *strlwr(const char *S);
This function takes, as argument, the string that needs to be converted. During conversion, if a Latin character were in uppercase, it would be converted to lowercase. Otherwise, it would stay “as if”. This means any symbol that is not a readable character would not be converted. |
#include <iostream> using namespace std; int main() { char CustomerAddress[] = "4812 LOCKWOOD Drive #F04"; cout << "Customer Address: " << CustomerAddress << endl; char *ShippingAddress = strlwr(CustomerAddress); cout << "Shipping Address: " << ShippingAddress << endl; return 0; }
This would produce:
Customer Address: 4812 LOCKWOOD Drive #F04 Shipping Address: 4812 lockwood drive #f04
The strupr() Function |
The strupr() function is used to convert a string to uppercase. Its syntax is: |
char *strupr(const char *S);
Each lowercase character in the function’s argument, S, would be converted to uppercase. Any character or symbol that is not in lowercase would not be changed. |
#include <iostream> using namespace std; int main() { char Drink[] = "100% Apple Juice"; char *SayItLoud; cout << "What is that drink? " << Drink << endl; SayItLoud = strupr(Drink); cout << "Say it loud: " << SayItLoud << endl; return 0; }
This would produce:
What is that drink? 100% Apple Juice Say it loud: 100% APPLE JUICE
Formatting Strings |
|
The sprintf() Function |
The sprintf() function is used to format data and specify how it should display. Its syntax is: |
int sprintf(char* Buffer, const char* S, Arguments…);
This function takes at least two arguments and could take more. The first argument is a null-terminated string that could display one or a few words and the formula to use when displaying the second or more argument. To display a value as part of the Buffer, type a double-quote followed by the string if any, followed by the % sign, follow by one of the following characters: |
|
|
||
Previous | Copyright © 2000-2016, FunctionX, Inc. | Next |
|