DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
No More String Errors - String(C++)

Reserve

Let's say we wanted to write a program, called cleanup, which changed all occurrences of certain words to certain other words. And let's say we wanted to keep the file in core to do some in-core processing. We might write it as follows:

   main()
   {
      String old[4];
      String new[4];
      old[0]="Rhodesia";    new[0]="Zimbabwe";
      old[1]="Alcindor";    new[1]="Abdul-Jabbar";
      old[2]="Congo";       new[2]="Zaire";
      old[3]="Bambergers";  new[3]="Macys";
   

String in; String out; while(cin >> in) { for(int i=0;i<3;i++) if(in == old[i]) in = new[i]; out += in; char c; while((c=cin.peek())==' ' || c=='\ t' || c=='\ n') { cin.get(c); out += c; } } cout << out; }

This is a perfectly good way of accomplishing this. However, if the file is large, some time will be taken up re-allocating space as out_file grows larger. In cases like this, the user can gain some efficiency by changing the above declaration of out_file to be: String out_file; out_file.reserve(FLSIZ); where FLSIZ is the approximate size of the file. Hint: Use reserve when the String will be long, you have an idea how long the String will end up, and the String is appended to in small increments.


Previous topic: Reverse

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005