Using Strings in C++

You can concatenate strings with the + operator as in Pascal, but remember that C++ encloses string literals within double quotes (e.g. "Hill") rather than within single quotes. C++ strings have many inbuilt routines. Here we demonstrate length(), at(), find(), append() and insert(). A copy of the output follows the code.

#include <iostream>

using namespace std;

int main()

{
  string forename = "Jessica";
  string marriedName = "Ennis-Hill";
  string fullName = forename + " " + marriedName; //concatenating using the + operator
  cout << "Full name: " << fullName << endl;
  cout << "Length of full name: " << fullName.length() << endl;
  cout << "Initial plus married name: " << forename.at(0) << " " << marriedName << endl; // could use forename[0] instead

  int hyphenPos = marriedName.find('-');
  string maidenName(marriedName, 0, hyphenPos); // using constructor
  cout << "Maiden name: "  << maidenName << endl;
  string husbandSurname(marriedName, hyphenPos + 1, marriedName.length() - hyphenPos);
  cout << "Husband's surname: "  << husbandSurname << endl;
  string husbandName("Andy");
  cout << "Husband's forename: " << husbandName << endl;
  husbandName.append(husbandSurname);
  husbandName.insert(4, " ");
  cout << "Husband's full name: " << husbandName << endl;

  return 0;
}
    

Output:

Full name: Jessica Ennis-Hill
Length of full name: 18
Initial plus married name: J Ennis-Hill
Maiden name: Ennis
Husband's surname: Hill
Husband's forename: Andy
Husband's full name: Andy Hill
Programming - a skill for life!

How to apply your knowledge of Pascal when learning C/C++