Inside Delphi 2006 (Wordware Delphi Developers Library)
The AnsiString class is the C++Builder equivalent of the Delphi string type. To use AnsiStrings in your application, you have to include the vcl.h header file, and the easiest way to do that is to check the Use VCL check box in the New Console Application dialog box, as shown in Figure 10-2.
The difference between the AnsiString class in C++Builder and the Delphi string type is mostly in syntax. The following table shows Delphi string related functions and the corresponding methods found in the AnsiString class. Note that when you include the vcl.h header file, you can use Delphi IntToStr and StrToInt functions to convert AnsiStrings to int and backward.
Delphi Function | AnsiString Method |
---|---|
Pos(Substring, String) | AnsiString.Pos(AnsiString) |
Copy(String, Index, Count) | AnsiString.SubString(Index, Count) |
Length(String) | AnsiString.Length() |
Delete(String, Index, Count) | AnsiString.Delete(Index, Count) |
Insert(SrcString, DestString, Index) | AnsiString.Insert(SrcString, Index) |
By default, you cannot display AnsiStrings using the cout object. Instead, you have to use the AnsiString's c_str() function to temporarily acquire a pointer to the AnsiString's internal null-terminated character array. But if you #define VCL_IOSTREAM before including the vcl.h header file, you will be able to pass AnsiStrings directly to cout.
The following listing shows how to use AnsiStrings in C++Builder applications.
Listing 10-11: Using AnsiStrings
#include <iostream.h> #include <conio.h> #define VCL_IOSTREAM #include <vcl.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) { /* displaying strings */ AnsiString s = "Borland AnsiString Class"; cout << s.c_str() << endl; cout << s << endl; // only if you've #defined VCL_IOSTREAM /* Find substring using Pos() */ if (s.Pos("Borland") > 0) cout << "The string contains \"Borland\"" << endl; /* Find char in string, you can use Pos or do it manually */ /* To determine the string's length, use the Length() method */ for(int x = 1; x <= s.Length(); x++) { if(s[x] == 'A') { cout << "Found 'A' in the string." << endl; break; } } /* use the Insert method to insert substrings into the string */ AnsiString s2 = "Windows,SysUtils,Forms;"; for(int x = 1; x <= s2.Length(); x++) { if(s2[x] == ',') s2.Insert(' ', ++x); } cout << s2 << endl; /* to copy a part of a string, use the SubString method */ AnsiString s3 = s.SubString(1, s.Pos(" Class")); cout << s3 << endl; // "Borland AnsiString" /* deleting a part of a string */ AnsiString s4 = s3; int pos = s4.Pos(' '); s4.Delete(pos, s4.Length() - pos); cout << s4 << endl; /* Borland */ /* converting string to int */ AnsiString s5 = "1234"; long num = StrToInt(s5); cout << num << endl; /* convert int to string */ AnsiString s6 = IntToStr(789); cout << s6.c_str() << endl; getch(); return 0; }