Useful C-String and C String Functions


Useful C-String and C++ String Functions

The cstring standard library provides a number of functions that are useful when working with null terminated character arrays, or C-strings. The string standard library provides a number of functions that are useful when working with the C++ string class.  This section will discuss together the functions you use with a C-string and the C++ string class, respectively, to perform several common tasks .

Determining the Length of a String

You use the strlen function to determine the length of a C-string. The strlen function takes one argument, which may be a character array, a pointer to a character array, or a literal string. This function returns an integer representing the number of characters , not including the null character. The following code fragment illustrates the use of the strlen function:

 int len; len = strlen("Jeff") // len is 4 char* stinkydog = "Dante"; len = strlen(stinkydog); // len is 5 char name[80] = "Devvie"; len = strlen(name); // len is 6 char crazydog[80] = "Micaela"; len = strlen(crazydog); // len is 7 

The strlen function is particularly useful in determining the length of a character array. For example, the following code fragment illustrates use of the strlen and isdigit functions to validate a social security number which, to be valid, must be exactly 11 characters long and consist of three digits, a dash, two digits, a dash, and four digits:

 bool isValidSSN(char* strInput) {  if (!strlen(strInput) == 11)  return false;  for (int x = 0; x < 11; x++)  {  if (x == 3  x == 6)  {  if (strInput[x] != '-')   return false;  }  else  {  if (!isdigit(strInput[x])  return false;  }  }   return true; } 

The C++ string class member functions that are comparable to the effect of strlen are length and size . Neither has any arguments, and both return an integer representing the length of the string. The following code fragment illustrates the use of the length and size member functions:

 string s = "Jeff Kent";    cout << s.length(); // outputs 9    cout << s.size(); // also outputs 9 

Assigning a Value to a String

You cannot assign the value of one C-string to another with an assignment operator, such as in the following code fragment:

 char* target = "Jeff Kent"; char source[80] = "Micaela"; target = source; 

The value of source is the base address of the target array. Thus, the assignment operator assigns the address of source to target, not the value of source to target.

Instead, you use the strcpy function to assign the value of one C-string (the source string) to another C-string (the target string). The strcpy function takes two arguments. The first argument, the target string, is a pointer to a character array. This argument cannot be a string literal since a value is being assigned to it. The second argument, the source string, may be a character array, a pointer to a character array, or a string literal. The following code fragment illustrates the use of the strcpy function:

 char* target = "Jeff Kent";    char source[80] = "Micaela";    strcpy(target, source); 

You need to be careful when using the strcpy function that the source C-string is not larger than the target C-string. To avoid this problem, you can use the strncpy function. This function has a third argument, an integer, representing how many characters to copy from the source C-string to the target C-string. The following code fragment illustrates the use of the strncpy function:

 char* target = "Jeff Kent";    char source[80] = "Micaela";    strncpy(target, source, 9); 

In contrast to C-strings, you may use the assignment operator to assign the value of one C++ string class variable to another, such as in the following code fragment:

 string target = "Jeff Kent";    string source = "Micaela";    target = source; 

Appending to a String

The strcpy function overwrites the contents of the target C-string with the contents of the source C-string. Sometimes you don t want to overwrite the contents of the target C-string, but instead add, or append, to its contents with the contents of the source C-String. Under these circumstances, use the strcat function, the cat being shorthand for concatenate, which is a longer way of saying append.

The strcat function, like the strcpy function, takes two arguments, the source target, a variable pointer to a character array, and the source C-string, which may be a character array, a pointer to a character array, or a string literal. The following code fragment illustrates the use of the strcat function:

 char target[80] = "Jeff";    char* source= " Kent";    strcat(target, source);    cout << target; // outputs "Jeff Kent" 

As with the strcpy function, you need to make sure when using the strcat function that the source string is large enough to accommodate the addition of the target C-string.

You can append the value of one C++ string class variable to another with the combined addition and assignment operator, such as in the following code fragment:

 string target = "Jeff";    string source = " Kent";    target += source;    cout << target; // outputs "Jeff Kent" 

Comparing Two Strings

You cannot use relational operators to compare the value of one C-string to another, such as in the following code fragment:

 char str1[80] = "Devvie Kent";    char str2[80] = "Devvie Kent";    if (str1 == str2)     cout << "The two C-strings are equal";    else     cout << "The two C-strings are not equal"; 

The output will always be: The two C-strings are not equal. The reason is that the value of each array name is the base address of that array. Thus, the comparison is not of values, but of addresses. Two variables cannot have the same address, so the result of the comparison for equality will be false.

Instead, you use the strcmp function to compare the values of two C-strings. The strcmp function has two arguments, the two C-strings to be compared. This function returns 0 if the two C-strings are equal in value. This is demonstrated by the following code fragment:

 char str1[80] = "Devvie Kent";    char str2[80] = "Devvie Kent";    if (strcmp(str1, str2 == 0))     cout << "The two C-strings are equal";    else     cout << "The two C-strings are not equal"; 

The call to the strcmp function could be changed to:

 if (!strcmp(str1, str2)) 

This works since 0 is logical false, so with the logical ! operator the result of logical false is changed to logical true.

The strcmp function returns a negative value if the first C-string is less than the second one, a positive value if the first C-string is greater than the second one. In this context of comparing two C-strings, whether one string is less or greater than another involves a comparison of the ASCII value of the two strings, starting with the first character, and continuing to each succeeding character as long as it takes to break the tie. Table 12-2 illustrates the results of several comparisons:

Table 12-2: Results of String Comparisons

First String (str1)

Second String (str2)

strCmp(str1, str2)

Reason

Jeff

jeff

negative

j has a higher ASCII value than J

aZZZ

Zaaa

positive

a has a higher ASCII value than Z

chess

check

positive

First three characters are the same, but fourth letter of first C-string, s, has higher ASCII value than fourth character of second C-string, c.

Jeff

Jeffrey

negative

First four characters are the same, but fifth character of second C-string, r, has a higher ASCII value than null character in the fifth position of the first C-string

Because three different return values are possible, the strcmp function often is used in an if / else if / else structure, as in the following program:

 #include <iostream> #include <cstring> using namespace std; int main(void) {  char str1[80], str2[80];  cout << "Enter first string: ";  cin >> str1;  cout << "Enter second string: ";  cin >> str2;  if (strcmp(str1, str2) == 0)  cout << "The two C-strings are equal";  else if (strcmp(str1, str2) > 0)  cout << "The first C-string is larger";  else   cout << "The second C-string is larger"; return 0; } 

The following are several sample inputs and outputs:

 Enter first string: Jeff Enter second string: Jeff The two C-strings are equal === Enter first string: Jeff Enter second string: jeff The second C-string is larger  === Enter first string: chess Enter second string: check The first C-string is larger === Enter first string: Jeff Enter second string: Jeffrey The second C-string is larger === 

By contrast, you can use relational operators to compare two variables of the C++ string class. Whether one string is less than or greater than another works the same way for the C++ string class as it does for C-strings. The following code fragment is illustrative :

 string str1 = "Jeff";  string str2 = "jeff";  string str3 = "Jeffrey";  str1 < str2; // true  str3 > str1; // true  str2 > str3; // true 

Conversion Between a C-String and a Number

The cstdlib standard library provides several functions for converting the C-string representation of a number to a numeric data type, as well as the reverse.

The atoi function s name is an acronym for ASCII to integer. This function has one argument, a C-string, and returns the integer that the C-string represents. The following code fragment demonstrates how the atoi function works:

 int num = atoi("7654"); 

The atoi function does not check if its argument can be converted to a numeric value. Additionally, the C++ programming language does not define the consequences if the argument cannot be converted to a numeric value. For example, the return value of an expression such as atoi("12Jeff") might be 12, the compiler attempting to perform the conversion from a character array to a number until a non-digit is reached. However, the return value instead could be 0, indicating the conversion could not be completed successfully.

The atoi function often is used in connection with a program that first has the user input a number into a character array, then checks if the character array represents a number before using the atoi function. This is demonstrated by the following program:

 #include <iostream> #include <cstring> using namespace std; int main(void) {  char input[80];  int num;  cout << "Enter an integer: ";  cin >> input;  for (int x = 0; x < strlen(input); x++)  {  if (x == 0)  {  if (!isdigit(input[x]) && input[x] != '-')  return false;  }  else   {  if (!isdigit(input[x]))  return false;  }  }  num = atoi(input);  cout << num;  return 0; } 

The advantage of having the user input a number into a character array instead of an integer is to avoid a run-time error or garbage data if the input is non-numeric. The character array then is checked to see if its value is the representation of a number. Since the number may be negative, the first character may be a dash as well as a digit. If the value of the character array is confirmed to be the representation of a number, then the atoi function is used to assign that value to an integer variable.

The atol function, standing for ASCII to Long, and the atof function, meaning ASCII to Float, work the same way as the atoi function except that their arguments are C-string representations of a long and float, respectively, and their return values likewise are a long and a float, respectively.

The C++ string class has no member functions that correspond to atoi, atol, or atof. However, a useful alternative is to first assign the value of a string to a character array using the c_str member function, after which atoi, atol, or atof could be used with the character array:

 string name = "123";  char str1[80];  strcpy(str1, name.c_str());  int num = atoi(str1); 

The data member function of the C++ string class also could be used to the same effect. The call to the strcpy function then would be the following:

 strcpy(str1, name.data()); 

Finally, the itoa function is the converse of the atoi function, standing for Integer to ASCII. The itoa function takes three arguments, the integer value to be converted, a pointer to the C-string to which the string representation of that integer will be assigned, and the number that represents the base of the converted value. The following code fragment shows how the itoa function may be used to assign to the character array intArray the C-string representation of the number 776 in base 10:

 char intArray[20];  itoa (776, intArray, 10); 



C++ Demystified(c) A Self-Teaching Guide
C++ Demystified(c) A Self-Teaching Guide
ISBN: 72253703
EAN: N/A
Year: 2006
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net