Strings

 

String Fundamentals

A string is a group printable letters of symbols. They can be grouped to create a single symbol or combined to produce a word or a sentence. The symbols are aligned in the computer memory in a consecutive manner so the last symbol is the null character. Here is an example:

M a t h e m a t i c s \0

Such a value is called a null-terminated string because the last symbol is a null-terminated character "\0". When allocating space for such a string, the space must be provided as the number of its characters + 1.

Like most other variables, to use a string, you can first declare a variable that would hold it.

To declare a string variable, you can use the char data type and create an array of symbols. Here are two examples:

char StrName[20];
char *Sentence;

The easiest way to initialize one of these variables is to give it a value when the variable is declared. Once it has been initialized, such a variable can be used in any function that can take advantage of it. Here is an example:

void CExoView::OnDraw(CDC* pDC)
{
    char *StrName = "Euzhan Palcy";

    pDC->TextOut(20, 22, StrName, 12);
}

When a string variable has been initialized, the string the variable holds is called its value. In the example above, Euzhan Palcy is the string value, or simply the value, of the StrName variable.

Allocating Space for a String

An alternative to using a pointer to declare an array of characters is provided by the StrAlloc() function. Its syntax is:

char *__fastcall StrAlloc(Cardinal Size);

When calling this function, provide the estimated number of characters of the string as the Size argument. The function creates and reserves an amount of space to accommodate the string that will be stored in the space. The space is filled with the empty string. The space is not left unoccupied or empty. It is filled with an empty string. The function returns a pointer to the beginning of the reserved address. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
#include <vcl.h>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    char *Major;;

    Major = StrAlloc(10);
    cout << "After allocation before initialization, what is the Major?\n";
    cout << "Major: " << Major << endl;

    Major = "Computer Sciences";
    cout << "\nAfter allocation and initialization, what is the Major?\n";
    cout << "Major: " << Major << endl;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

After allocation before initialization, what is the Major?
Major:

After allocation and initialization, what is the Major?
Major: Computer Sciences

Press any key to continue...

 

The Length of a String

The length of a string is the number of characters that the string contains. To get the length of a string declared with the char data type or one of the Win32 API's data types, you can use the strlen() function. Its syntax is:

size_t strlen(const char *String);

This function returns the number of characters of the String argument. Here is an example:

void CExoView::OnDraw(CDC* pDC)
{
	char StrName[] = "Euzhan Palcy";
	int Len = strlen(StrName);

	pDC->TextOut(20, 22, StrName, Len);
}

Character Validation 

Every time the user types a character in a text-based control, this is referred to as a keystroke. When performing data entry, even if the user presses two keys simultaneously (to enter an uppercase letter or to type a special character), only one character is entered at a time. You can find out what character the user has entered in your application using appropriate functions. Some functions are used to categorize the types of characters on the keyboard. The functions used for these validations are as follows:

Function Meaning
 int isalpha(int c); Returns true if c is an alphabetic character. Otherwise, returns false
 int islower(int c); Returns true if c is an alphabetic character in lowercase. Otherwise, returns false.
 int isupper(int c); Returns true if c is an alphabetic character in uppercase. Otherwise, returns false
 int isdigit(int c); Returns true if c is a digit. Otherwise, returns false
 int isxdigit(int c); Returns true if c is a hexadecimal digit. c must be one of the following 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, A, B, C, D, E, or F. Otherwise, returns false.
 int isalnum(int c); Returns true is c is between 0 and 9 or if c is between a and z or if c is between A and Z. Otherwise, returns false.
 int isascii(int c); Returns true if c is an ASCII character. Otherwise, returns false
 int ispunct(int c); Returns true if c is a punctuation character. Otherwise, returns false.
 int isprint(int c); Returns true if c is a printable character. Otherwise, returns false.
 int isgraph(int c); Returns true if c is a printable character and is not an empty space.
 int isspace(int c); Returns true if c is an empty space

Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
//---------------------------------------------------------------------------
char __fastcall GetGender()
{
    char g;

    cout << "What is your gender(m/f)? ";
    cin >> g;

    if( isalpha(g) )
        return g;
    else
        return 'f';
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    char Gender;

    Gender = GetGender();

    cout << "\nYour gender: ";
    if( Gender == 'm' || Gender == 'M' )
        cout << "Male";
    else
        cout << "Female";
    return 0;
}
//---------------------------------------------------------------------------

 

 

The String Copy

Copying a string is equivalent to assigning all of its characters to another string. After copying, both strings would have the same value. To copy a null-terminated string, you can use the strcpy() function. Its syntax is:

char *strcpy(char *strDestination, const char *strSource);

The strDestination argument is the target string.

The strSource argument holds the value of the string that needs to be executed. During execution, its value would be assigned to the strDestination variable. After execution, this function returns another string has the same value as strDestination.


    

This would produce:

The S

String Concatenation

String concatenation consists of appending one string to another, similar to building a house next to an existing one. To append one to another, you can 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 (it looks like the C++ Standard folks were Assembly programmers). 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. Therefore, the strcat() function is be used to add two strings and it returns a new string as a result of Destination + Source. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
#include <vcl.h>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    char *Make  = "Ford ";
    char *Model = "Explorer";
    char *Car;

    cout << "Originally\nMake = " << Make << endl;

    Car = strcat(Make, Model);

    cout << "\nAfter concatenating\nMake = " << Make << endl;
    cout << "\nCar  = " << Car << endl;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Originally
Make = Ford

After concatenating
Make = Ford Explorer

Car  = Ford Explorer

Press any key to continue...

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 of the strncat() function is:

char* strncat(char* Destination, const char* Source, int Number);

Besides the same arguments as the strcat() function, the Number argument is used to specify the number of characters considered from Source. To perform the concatenation, the compiler would count Number characters from left to right of the Source string. These characters would be added to the right of the Destination string. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
#include <vcl.h>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    char *Make  = StrNew("Ford ");
    char *Model = StrNew("Explorer");

    cout << "Originally, Make = " << Make;

    strncat(Make, Model, 3);

    cout << "\n\nAfter concatenating, Make = " << Make;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Originally, Make = Ford

After concatenating, Make = Ford Exp
Press any key to continue...
 

Working With Individual Characters

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 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 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.

 

Formatting Strings

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:

Character Used to Display Character Used to Display
s A string f Floating-point value
c A character d An integer
 

Introduction to the STL's string Class

The Standard Template Library (STL) provides a class that can be used for string manipulation. This class is called basic_string and it was type-defined as string. Therefore, to declare a variable using the STL's string class, use one of its constructors. For example, you can use the default constructor as follows:

string FirstName;

The STL's string class is not natively supported in MFC applications. Therefore, in order to use it, you must convert its value to a null-terminated string. To allow this, the string class provides the c_str() member function. Its syntax is:

const E *c_str() const;

Here is an example:

void CExoView::OnDraw(CDC* pDC)
{
	string StrName = "Central African Republic";

	pDC->TextOut(20, 22, StrName.c_str(), 24);
}

STL Length of a String

To get the length of a string declared using the string class, call the length() member function. Its syntax is:

size_type length() const;

You can also get the same result by calling the size() method whose syntax is:

size_type size() const;

Here is an example:

void CExoView::OnDraw(CDC* pDC)
{
	string StrName = "Central African Republic";

	int Len = StrName.length();
	pDC->TextOut(20, 22, StrName.c_str(), Len);
}

Introduction to the CString Class

The MFC library provides its own data types and a class for string manipulation. To declare a string with the CString class, use one of the CString constructors as follows:

CString();
CString(const CString& stringSrc);
CString(TCHAR ch, int nRepeat = 1);
CString(LPCTSTR lpch, int nLength);
CString(const unsigned char* psz);
CString(LPCWSTR lpsz);
CString(LPCSTR lpsz);

The default constructor is used to declare an empty string. To initialize it, you can assign it a string value of your choice. Here is an example:

void CExoView::OnDraw(CDC* pDC)
{
	CExoDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);

	CString Country = "Information Superhighway";

	pDC->TextOut(20, 22, Country);
}

The CString(const unsigned char* psz), the CString(LPCWSTR lpsz), and the CString(LPCSTR lpsz) constructors can be used to declare an initialize a string by providing its value in the parentheses of the variable. The value is provided as a null-terminated string. Here is an example:

void CExoView::OnDraw(CDC* pDC)
{
	CExoDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);

	CString Country("Information Superhighway");

	pDC->TextOut(20, 22, Country);
}

The CString(const CString& stringSrc) copy constructor allows you to make a copy of a CString variable and assign it to another CString variable.

To declare a CString variable that has a single character, use the CString(TCHAR ch) constructor. The character can be included between single-quotes. Here is an example:

void CExoView::OnDraw(CDC* pDC)
{
	CExoDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);

	CString Letter('A');

	pDC->TextOut(20, 22, Letter);
}

If you want the character to be repeated more than once, use the constructor as CString(TCHAR ch, int nRepeat = 1). In this case, the value of nRepeat can be used to specify the number of times the string would contain the ch character.

Copying a String

The strncpy() function works like the strcpy() function. Itis syntax:

char* strncpy(char* Destination, const char* Source, int Number);

 

Validating a Character

Every time the user

Function Meaning
 int isalpha(int c); Returns true if c is an alphabetic character. Otherwise, returns false
 int islower(int c); Returns true if c is an alphabetic character in lowercase. Otherwise, returns false.
 int isupper(int c); Returns true if c is an alphabetic character in uppercase. Otherwise, returns false
 int isdigit(int c); Returns true if c is a digit. Otherwise, returns false
 int isxdigit(int c); Returns true if c is a hexadecimal digit. c must be one of the following 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, A, B, C, D, E, or F. Otherwise, returns false.
 int isalnum(int c); Returns true is c is between 0 and 9 or if c is between a and z or if c is between A and Z. Otherwise, returns false.
 int isascii(int c); Returns true if c is an ASCII character. Otherwise, returns false
 int ispunct(int c); Returns true if c is a punctuation character. Otherwise, returns false.
 int isprint(int c); Returns true if c is a printable character. Otherwise, returns false.
 int isgraph(int c); Returns true if c is a printable character and is not an empty space.
 int isspace(int c); Returns true if c is an empty space
 

Characters Cases

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.

 

Strings Comparisons

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

  • A negative value if S1 is less than S2
  • 0 if S1 and S2 are equal
  • A positive value if S1 is greater than S2

To compare two strings, you can use the StrComp() function. Its syntax is:

int StrComp(const char *Str1, const char *Str2);
 

String Concatenation

String concatenation consists of appending one string to another, similar to building a house next to an existing one. To append one to another, you can use the strcat() function. Its syntax is:

char *strcat(char *Destination, const char *Source);

 

Sprint Formatting

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:

Character Used to Display Character Used to Display
s A string f Floating-point value
c A character d An integer
 
 

Previous Copyright © 2003 FunctionX, Inc. Next