Programming & Scripting Tutorials

C++: String Manipulation





In this lesson we are going to cover string manipulation.

Firstly we will start with some basic string manipulation, then we can move on.

1)Strings can be 'stuck together' using the + operator:

string string1 = "this is";
string string2 = " one string";
string string3 = string1 + string2;


2) A strings length can be found via the length or size function:

string String = "dev-hq.co.uk";
int len = String.length();
cout << len << endl;

3) Strings can be treated like char arrays in some circumstances:

string String = "dev-hq.co.uk";
cout << String[0] << endl;

4) You can get different parts of the string (using substr):

string String = "abcdefghijklmnopqrstuvwxyz";
string abc = String.substr(0, 3);
cout<< "First three letters of alphabet = " << abc << endl;

This works by getting the letter to start on, and then counting up a certain number of letters.
In this case we start with 0 and go up 3.

5) You can remove parts of strings using the erase function (this also takes a starting point and then a length):

string RemoveLOL = "remove LOL";
cout << RemoveLOL << endl;
RemoveLOL.erase(7, 3);
cout << RemoveLOL << endl;

6) You can insert bits into strings with the insert function:

string String = "Hlo!";
String.insert(1, "el");
cout<< String <<endl;


---

Manipulating strings in C++ is very useful, as you can easily modify what will be outputted or read by the program.


This C++ tutorial was written by


Back to C++

Advertisement: