C++ Strings
June 09, 2020 by Jane

Definition:
 

#include<string>

string empty; // default uninitialized string is ""

string str1 = "C++ string";

 

Common String Methods

length() returns the length of the string, or the number of characters in the string

substr([start], [opt length]) returns a substring of the original starting at index "start" and continue for "length" characters. If length is not given, assume the substring will continue till end of original string

E.g.

string greet = "hello";

string substring = greet.substr(1, 4); // substring contains "ello"

 

Formatting Strings and Numbers

setw([width])

  • print the string with specified width, needs to be set for every item

setfill([filler character])

  • used together with setw() to format or pretty-print strings/numbers 

setprecision([precision])

  • print the number with the precision specified, only needs to be used once to set precision for the stream
  • used fixed if trailing zeros are needed (see example below)

 

E.g. 1. setfill() + setw()

cout << setfill ('x') << setw (10); cout << 77 << endl; // prints xxxxxxxx77

 

E.g. 2. fixed + setprecision()

for (int year = 8; year <= 10; year++) {
    double interest = balance * rate / 100;
    balance = balance + interest;
    cout << setw(2) << year << ": " << fixed << setprecision(2) << balance << endl;
}

// Output:

 8: 14071.00 // because we set "fixed", the trailing zeros are there; setprecision doesn't actually ensure trailing zeros are added
 9: 15513.28 // notice that 8 and 9 are flush with 10 because we had setw(2) on the year variable.
10: 16288.95