Lesson Home

Strings

 

Character and their Cases

 

Character Cases

Each alphabetic character in the English language has two representations: lowercase and uppercase. Characters in lowercase are: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, and z. Their equivalent characters in uppercase are represented as A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Characters used for counting are called numeric characters; each one of them is called a digit. They are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. There are other characters used to represent things in computer applications, mathematics, and others. Some of these characters, also called symbols are ~ , ! @ # $ % ^ & * ( ) _ + { } ` | = [ ] \ : " ; ' < > ? , . / These characters are used for various reasons and under different circumstances. For example, some of them are used as operators in mathematics or in computer programming. Regardless of whether a character is easily identifiable or not, in C++, all these symbols are character types and can be declared using the char data type followed by a name.

The C/C++ char data type is an 8-bit value. To accommodate for Unicode issues, Managed C++ provides a 16-bit data type used to declare and manipulate characters. The data type is called __wchar_t and we will use it regularly throughout our lessons for character variables.

To initialize a __wchar_t variable using one of the symbols, type it between single quotes and on the right side of an assignment operator. Here are examples:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    __wchar_t Gender = 'm';
    __wchar_t MoneySymbol = '$';
    __wchar_t Multiplication = '*';
    __wchar_t NumberOne = '1';

    Console::WriteLine("A few characters");
    Console::Write("Gender:         ");
    Console::WriteLine(Gender);
    Console::Write("MoneySymbol:    ");
    Console::WriteLine(MoneySymbol);
    Console::Write("Multiplication: ");
    Console::WriteLine(Multiplication);
    Console::Write("NumberOne:      ");
    Console::WriteLine(NumberOne);

    Console::WriteLine();
    return 0;
}

This would produce:

A few characters
Gender:         m
MoneySymbol:    $
Multiplication: *
NumberOne:      1

Press any key to continue...

When declaring a variable using __wchar_t, to indicate that the character should be considered as a normal char value, you can precede its declaration with L as follows:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    __wchar_t Gender = L'm';

    Console::WriteLine("A few characters");
    Console::Write("Gender: ");
    Console::WriteLine(Gender);

    Console::WriteLine();
    return 0;
}

Some of the C/C++ functions we use in our lessons are defined in the string header file of the std namespace. Therefore, in order to use them, make sure you specify that you will use the std namespace.

 

Converting a Character to Uppercase

An alphabetic character, for any reason judged necessary, can be converted from one case to another. The other characters, non-alphabetic symbols, and the numbers, do not have a case and therefore cannot be converted in cases.

The C/C++ language provides two functions used to convert a character from one case to the other.

To convert a lowercase character to uppercase, you can use the toupper() function. Its syntax is:

int toupper(int c);

This function simply takes one argument, the character that needs to be converted, c. If the character c is already in uppercase, nothing would change. If the character is a lowercase alphabetic character, the function would return it in uppercase. If the argument is not an alphabetic character, it would be kept “as-is”.

Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    __wchar_t Gender = 'm';

    __wchar_t Gdr = toupper(Gender);

    Console::WriteLine("Gender: {0}", __box(Gender));
    Console::WriteLine("Gender: {0}", __box(Gdr));

    Console::WriteLine();
    return 0;
}

This would produce:

Gender: m
Gender: M

Press any key to continue

 

Converting a Character to Lowercase

To convert a character to lowercase, you can use the tolower() function. Its syntax is:

int tolower(int c);

This takes one argument as the character to convert. If the argument c is not an alphabetic character, it would be kept “as-is”. If c is an uppercase alphabetic character, it would be converted to lowercase. If c is in lowercase, it would not be converted.

Validating a Character

Every time the user types a character, the action is 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
 

Introduction to Strings

 

The String as a Series of Characters

A string is a group of characters with the last character being "\0". A typical string, such as Pacifique, can be 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 C/C++ language ships with many functions that allow you to perform various types of operation on null-terminated strings.

 

String Declaration With the string Class

The C++ and its parent the C languages do not have a string data type. One of the solutions you can use consists of declaring a pointer to char, Char, or __wchar_t. You can then initialize such a variable using the assignment operator. Here are examples:

char *city = "Buenos Aires";

When declaring a string variable using __wchar_t, to consider the string as a pointer to char, you can precede it with L as follows:

__wchar_t *sentence = L"Managed C++ Programming";

Such a variable can be passed to Write or WriteLine to display on the screen. Here are examples:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    char      *city     = "Buenos Aires";
    __wchar_t *sentence = L"Managed C++ Programming";

    Console::WriteLine(city);
    Console::WriteLine(sentence);

    Console::WriteLine();
    return 0;
}

This would produce:

Buenos Aires
Managed C++ Programming

Press any key to continue

C++ uses a library called Standard Template Library (STL) to take care of this. To declare a string in C++, you can use the string class, as we have done in previous lessons. Here is an example:

string bookTitle;

To initialize a string variable, you can assign it a word or sentence between double-quotes. Here is an example:

string bookTitle = "Managed C++ Programming";

The string class also provides various constructors used to declare it. One of these constructors allow you to initialize a string variable using parentheses. You can use this constructor to declare and initialize the above string variable as follows:

string bookTitle("Managed C++ Programming");

To display a string variable in Write or WriteLine, you can call its c_str() method. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    string bookTitle = "Managed C++ Programming";

    Console::Write("Book Title: ");
    Console::WriteLine(bookTitle.c_str());

    Console::WriteLine();
    return 0;
}
 

Introduction to the Managed String Class

Like most other programming environments or libraries, Managed C++ ships with a class used to create and manipulate strings. The class is called String. Like most other classes of the Microsoft .NET Framework, to declare a string using the String class, use the * operator. Here is an example:

String *sentence;

If you declare a String variable without initializing it, its memory space is made empty. Therefore, before using the variable, you should initialize it. The String class provides three main options to initialize a String variable. One of the techniques you can use involves a constructor and the String class provides many of them. After initializing the variable, you can pass it to Write or WriteLine to display on the screen. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    String *bookTitle = "Managed C++ Programming";

    Console::Write("Book Title: ");
    Console::WriteLine(bookTitle);

    Console::WriteLine();
    return 0;
}

When initializing a String variable or assigning a value to it, you can precede the opening double-quote with L to indicate that the string will be converted to a regular letter-based string. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    String *bookTitle = L"Managed C++ Programming";

    Console::Write("Book Title: ");
    Console::WriteLine(bookTitle);

    Console::WriteLine();
    return 0;
} 

For a better management of a string assigned to a String variable or for a double-quoted string used as a String value, you should precede it with S. Here is an example:

// This is the main project file for VC++ application project 
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;

int _tmain()
{
    // TODO: Please replace the sample code below with your own.
    String *bookTitle = S"Managed C++ Programming";

    Console::Write(S"Book Title: ");
    Console::WriteLine(bookTitle);

    Console::WriteLine();
    return 0;
}

You can also initialize a String variable with a variable declared using a pointer to char, Char, or __wchar_t.

Author Note Managed C++ is an extremely huge language and supports more libraries than most languages in the industry (Managed C++ by itself natively supports C, C++, STL, ATL, Win32, .NET, etc). If we try to cover all possible ways to use strings in Managed C++, this whole book would contain only strings. To reduce the number of instructions, unless specified otherwise, from now on, we will use only the String class.

 

The Length of a String

In many operations, you will need to know the number of characters a string consists of. To get the size of a string, The String class provides the Length member variable. 

 

Strings and Data Reading

 

String Request

So far, to request a value from the user, we were using cin. The cin extractor of C++ has many problems, one of them is that it has a hard time reading an entry that contains space. Managed C++ completely solves this problem using the Console class.

To request a natural number, you can use the Console::Read() method (because of some of its limitations, we will hardly use that method in this book). To request a String value from the user, the Console class provides the ReadLine() method. Its syntax is:

String* ReadLine();

This function retrieves a String value from the keyboard. It expects the user to type a series of characters and empty spaces until he or she presses Enter. Once the user presses Enter, the compiler considers that the string is complete. It retrieves and returns its value, which you can use as you see fit. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
	String *FullName;
	
	// Request the name
	Console::Write(S"Enter you name: ");
	FullName = Console::ReadLine();

	Console::Write("\nFull Name: ");
	Console::WriteLine(FullName);

	Console::WriteLine();
	return 0;
}

Here is an example of running the program:

Enter you name: Ferdinand Coly

Full Name: Ferdinand Coly

Press any key to continue

Like the WriteLine() method, when the ReadLine() function has finished its processing, it transfers the caret to the next line.

 

Converting a String to a Value

As far as the compiler is concerned, everything the user types using the keyboard is a string, whether it is an empty space, a letter, a symbol, a word, or a sentence. This implies that the compiler counts on you to define what to do with a string and how to do it. Therefore, if you want to get a value from the user, you can first request a string and then convert it to the desired value. This is relatively easily done because each data type provides a mechanism to perform such a conversion.

After getting a value from the user and storing it in a String variable, you can call the Parse() function of the data type to analyze the string value and see if it corresponds to the value of your choice. In the parentheses of Parse(), type the name of the String variable you just requested and assign the result to the necessary primitive variable. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
	Double HourlySalary, WeeklySalary;
	String *Sal;

	Console::Write("Enter your hourly salary: ");
	Sal = Console::ReadLine();
	HourlySalary = Double::Parse(Sal);

	WeeklySalary = HourlySalary * 40;

	Console::Write("\nWeekly Salary: ");
	Console::WriteLine(WeeklySalary);

         Console::WriteLine();

         return 0;
}

This would produce:

Enter your hourly salary: 12.52

Weekly Salary: 500.8

Press any key to continue

As seen previously, the String class also provides functions that allow it to convert a value to a primitive type. You can use such a function to convert a value gotten from the user to an appropriate type. Here is another example that uses different data types:

#using <mscorlib.dll>
using namespace System;

int main()
{
	String *CarMake, *CarModel;
	int CarYear;
	long Mileage;
	bool HasAirCondition;

	String *CY, *Miles, *HasAC;

	Console::WriteLine("Enter Car Registration Information");
	Console::Write("Make:    ");
	CarMake = Console::ReadLine();
	Console::Write("Model:   ");
	CarModel = Console::ReadLine();
	Console::Write("Year:    ");
	CY = Console::ReadLine();
	Console::Write("Mileage: ");
         Miles = Console::ReadLine();
	Console::Write("Air Condition (Type True or False)? ");
	HasAC = Console::ReadLine();
	
         CarYear = CY->ToInt32(0);
	Mileage = Miles->ToUInt32(0);
	HasAirCondition = HasAC->ToBoolean(0);

	Console::WriteLine("\nCar Registration");
	Console::Write("Make:    ");
	Console::WriteLine(CarMake);
	Console::Write("Model:   ");
	Console::WriteLine(CarModel);
	Console::Write("Year:    ");
	Console::WriteLine(CarYear);
	Console::Write("Mileage: ");
         Console::WriteLine(Miles);
	Console::Write("Has A/C: ");
	Console::WriteLine(HasAirCondition);

	Console::WriteLine();
	return 0;
}

Here is an example of running the program:

Enter Car Registration Information
Make:    Nissan
Model:   Sentra
Year:    1998
Mileage: 42785
Air Condition (Type True or False)? true

Car Registration
Make:    Nissan
Model:   Sentra
Year:    1998
Mileage: 42785
Has A/C: True

Press any key to continue

Strings and Data Formatting

Earlier, we saw that each of the primitive data types has a ToString() function that allows it to convert its value to a String type. Instead of using two Write() functions or a combination of Write() and WriteLine() function, you can convert a primitive value to a string and display it directly. To do this, you can provide two values to the Write() or WriteLine() function:

  1. The first part of the string provided to the Write() or WriteLine() function is the complete string value that would display to the user. This first string itself is made of two sections:
    1. The first section is a string in any way you want it to display
    2. The second is a number included between an opening curly bracket "{" and a closing curly bracket "}"
  2. The second part of the string provided to the Write() or WriteLine() function is the value, converted using ToString(), that you want to display.

Here are examples:

#using <mscorlib.dll>
using namespace System;

int main()
{
    String *FullName = "Anselme Bogos";
    int Age = 15;
    double HSalary = 22.74;

    Console::WriteLine("Full Name: {0}", FullName);
    Console::WriteLine("Age: {0}", Age.ToString());
    Console::WriteLine("Distance: {0}", HSalary.ToString());

    Console::WriteLine();
    return 0;
}

This would produce:

Full Name: Anselme Bogos
Age: 15
Distance: 22.74

Press any key to continue

The numeric value typed in the curly brackets of the first part is an ordered number. If you want to display more than one value, provide each incremental value in its curly brackets. The syntax used is:

Write("To Display {0} {1} {2} {n}", First, Second, Third nth);

You can use the sections between a closing curly bracket and an opening curly bracket to create meaningful sentence. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
    String *FirstName = "Anselme";
    String *LastName  = "Bogos";
    int Age = 15;
    double HSalary = 22.74, HoursWorked = 35.50;
    double WeeklySalary = HSalary * HoursWorked;

    Console::WriteLine("Full Name: {0} {1}", FirstName, LastName);
    Console::WriteLine("Age: {0}", Age.ToString());
    Console::WriteLine("Weekly Salary: {0} for {1} hours",
		     WeeklySalary.ToString(), HoursWorked.ToString());

    Console::WriteLine();
    return 0;
}

This would produce:

Full Name: Anselme Bogos
Age: 15
Weekly Salary: 807.27 for 35.5 hours

Press any key to continue

 

Type Formatting

 

To properly display data in a friendly and most familiar way, you can format it. Formatting tells the compiler what kind of data you are using and how you want the compiler to show it to the user. As it happens, you can display a natural number in a common value or, depending on the circumstance, you may prefer to show it as a hexadecimal value. When it comes to double-precision numbers, you may want to display a distance with three values on the right side of the fraction separator and in some cases, you may want to display a salary with only 2 decimal places.

The System namespace provides a specific letter that you can pass to the String::ToString() method for each category of data to display. The letters and their meanings are:

  Character Used For
  c C Currency values
  d D Decimal numbers
  e E Scientific numeric display such as 1.45e5
  f F Fixed decimal numbers
  g G General and most common type of numbers
  n N Natural numbers
  r R Roundtrip formatting
  x X Hexadecimal formatting

The necessary letter is passed to the ToString() method and is included between double-quotes. Here are examples:

#using <mscorlib.dll>
using namespace System;

int main()
{
    double Distance = 248.38782;
    int Age = 15;
    int NewColor = 3478;
    double HSalary = 22.74, HoursWorked = 35.5018473;
    double WeeklySalary = HSalary * HoursWorked;

    Console::WriteLine("Distance: {0}", Distance.ToString("E"));
    Console::WriteLine("Age: {0}", Age.ToString());
    Console::WriteLine("Color: {0}", NewColor.ToString("X"));
    Console::WriteLine("Weekly Salary: {0} for {1} hours",
                       WeeklySalary.ToString("c"), HoursWorked.ToString("F"));

    Console::WriteLine();
    return 0;
}

This would produce:

Distance: 2.483878E+002
Age: 15
Color: D96
Weekly Salary: $807.31 for 35.50 hours

Press any key to continue

 

String Cases

 

Conversion to Lowercase

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 be stay “as if”. This means any symbol that is not a readable character would not be converted.

#using <mscorlib.dll>
#include <string>
using namespace std;
using namespace System;

int main()
{
    char CustomerAddress[] = "4812 LOCKWOOD Drive #F04";

    Console::Write("Customer Address: ");
    Console::WriteLine(CustomerAddress);

    char *ShippingAddress = strlwr(CustomerAddress);

    Console::Write("Shipping Address: ");
    Console::WriteLine(ShippingAddress);

    Console::WriteLine();
    return 0;
}

This would produce:

Customer Address: 4812 LOCKWOOD Drive #F04
Shipping Address: 4812 lockwood drive #f04


Press any key to continue...

Conversion to Uppercase

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.

#using <mscorlib.dll>
#include <string>
using namespace std;
using namespace System;

int main()
{
    char Drink[] = "100% Apple Juice";
    char *SayItLoud;

    Console::Write("What is that drink? ");
    Console::WriteLine(Drink);

    SayItLoud = strupr(Drink);

    Console::Write("Say it loud:        ");
    Console::WriteLine(SayItLoud);

    Console::WriteLine();
    return 0;
}

This would produce:

What is that drink? 100% Apple Juice
Say it loud:        100% APPLE JUICE

Press any key to continue...
 

Strings Comparisons

 

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

  • 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
#using <mscorlib.dll>
#include <string>
using namespace std;
using namespace System;

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);

    Console::Write("The result of comparing ");
    Console::Write(FirstName1);
    Console::Write(" and ");
    Console::Write(FirstName2);
    Console::Write(" is\t");
    Console::WriteLine(Value1);
    Console::Write("The result of comparing ");
    Console::Write(FirstName2);
    Console::Write(" and ");
    Console::Write(FirstName1);
    Console::Write(" is\t");
    Console::WriteLine(Value2);
    Console::Write("The result of comparing ");
    Console::Write(LastName1);
    Console::Write(" and ");
    Console::Write(LastName2);
    Console::Write(" is\t");
    Console::WriteLine(Value3);

    Console::WriteLine();
    return 0;
}

This would produce:

The result of comparing Andy and Charles is     -1
The result of comparing Charles and Andy is     1
The result of comparing Stanley and Stanley is  0

Press any key to continue...
 

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

  • 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

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

  • 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

The strnicmp() Function

The strnicmp() function compares two strings without regard to their case but considering 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

  • 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

Copies of a String 

 

String Copy

The strcpy() function is used to copy one string into another string. In short, 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 left argument is the string that you are trying to replace. The right argument is the string that will be assigned to the left string. After the operation, the strcpy() function assigns the Source string to the Destination string. Here is an example:

#using <mscorlib.dll>
#include <string>
using namespace std;
using namespace System;

int main()
{
    char CarName1[] = "Ford Escort";
    char CarName2[] = "Toyota 4-Runner";

    Console::WriteLine("The String Copy Operation");
    Console::Write("First Car:  ");
    Console::WriteLine(CarName1);
    Console::Write("Second Car: ");
    Console::WriteLine(CarName2);

    strcpy(CarName2, CarName1);

    Console::WriteLine("\nAfter using strcpy()...");
    Console::Write("First Car:  ");
    Console::WriteLine(CarName1);
    Console::Write("Second Car: ");
    Console::WriteLine(CarName2);

    Console::WriteLine();
    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
Press any key to continue...
 

String Duplicate

The strdup() function is used to make a copy of a string and create a duplicate of that string. Its syntax is:

char* strdup(const char *Source);

This function takes as an argument the string you want to duplicate and returns the duplicated string. Here is an example

#using <mscorlib.dll>
#include <string>
using namespace std;
using namespace System;

int main()
{
    char *Imagination = "Imagination by transference";
    char *Transfer;
	
    Console::Write("Imagine this:  ");
    Console::WriteLine(Imagination);
    Console::Write("Transfer that: ");
    Console::WriteLine(Transfer);

    Transfer = strdup(Imagination);

    Console::Write("\nImagine this:  ");
    Console::WriteLine(Imagination);
    Console::Write("Transfer that: ");
    Console::WriteLine(Transfer);

    Console::WriteLine();
    return 0;
}

This would produce:

Imagine this:  Imagination by transference
Transfer that:

Imagine this:  Imagination by transference
Transfer that: Imagination by transference

Press any key to continue
 

Characters Copying

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

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

As a difference, the strncpy() function allows you to specify the number of characters that the compiler would copy from the Source to the Destination strings. The Number argument specifies the number of characters that will be copied from the Source string. Here is an example: 

#using <mscorlib.dll>
#include <string>
using namespace std;
using namespace System;

int main()
{
    char CarName1[] = "Ford Escort";
    char CarName2[] = "Toyota 4-Runner";

    Console::WriteLine("The String Copy Operation");
    Console::Write("First Car:  ");
    Console::WriteLine(CarName1);
    Console::Write("Second Car: ");
    Console::WriteLine(CarName2);

    strncpy(CarName2, CarName1, 8);

    Console::WriteLine("\nAfter using strncpy() for 8 characters\n");
    Console::Write("First Car:  ");
    Console::WriteLine(CarName1);
    Console::Write("Second Car: ");
    Console::WriteLine(CarName2);

    Console::WriteLine();
    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

Press any key to continue...
 

String Concatenation

 

Concatenating a String

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:

#using <mscorlib.dll>
#include <string>
using namespace std;
using namespace System;

int main()
{
    char *Make  = "Ford ";
    char *Model = "Explorer";
    char *Car;

    Console::WriteLine("Originally");
    Console::Write("Make:  ");
    Console::WriteLine(Make);
    Console::Write("Model: ");
    Console::WriteLine(Model);
    Console::Write("Car:   ");
    Console::WriteLine(Car);

    Car = strcat(Make, Model);

    Console::WriteLine("\nAfter concatenating");
    Console::Write("Make:  ");
    Console::WriteLine(Make);
    Console::Write("Model: ");
    Console::WriteLine(Model);
    Console::Write("Car:   ");
    Console::WriteLine(Car);

    Console::WriteLine();
    return 0;
}

This (was compiled using Visual C++ .Net 2002 and) produced:

Originally
Make:  Ford
Model: Explorer
Car:

After concatenating
Make:  Ford Explorer
Model: lorer
Car:   Ford Explorer

Press any key to continue

 

Characters Concatenation

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:

#using <mscorlib.dll>
#include <string>
using namespace std;
using namespace System;

int main()
{
    char *Make  = "Ford ";
    char *Model = "Explorer";

    Console::WriteLine("Originally");
    Console::Write("Make = ");
    Console::WriteLine(Make);

    strncat(Make, Model, 3);

    Console::WriteLine("\nAfter concatenating");
    Console::Write("Make = ");
    Console::WriteLine(Make);

    Console::WriteLine();
    return 0;
}

(In Visual C++ 2002) This would produce:

Originally
Make = Ford

After concatenating
Make = Ford Exp

Press any key to continue

 

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() Functionn

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.

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:

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

Here is an example that uses the sprintf() function:

#using <mscorlib.dll>
#include <string>
using namespace std;
using namespace System;

int main()
{
    char *Sentence = new char[40];
    int Pages = 488;

    sprintf(Sentence, "This book contains %d pages", Pages);

    Console::WriteLine(Sentence);

    Console::WriteLine();
    return 0;
}

This would produce:

This book contains 488 pages

Press any key to continue
 

 


Previous Copyright © 2004-2010 FunctionX, Inc. Next