Home arrow C and C+ arrow Strings in C++
Strings in C++ PDF
Thursday, 14 April 2011
This is a brief tutorial for working with strings in C++.

To compile C++ examples use:

  g++ example.cc -o example

Next sections shows examples of working with strings in C++.


Convert a C++ string to a C string
-----------------------------------------
This example will read content from a text file. The problem is that ifstream uses C strings and if we want to use C++ string variable we must first convert them to C string before using them with ifstream function members.

See the next example. We user c_str() function member to convert from C++ strings to C strings.

read a text from a file, use filname of C++ string type but we uses c_str() to first convert it to C string
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
  ifstream is;
  string myFile = "readme.txt";
  string strOne;
  int bufLength;
  char *buff;

  is.open(myFile.c_str());

  if (is.fail())
        return -1;

  is.seekg(0, ios::end);
  bufLength = is.tellg();
  is.seekg(0, ios::beg);

  buff = new char[bufLength];

  is.read(buff, bufLength);
  cout << buff;

  is.close();

  delete[] buff;
  return 0;
}



Length of a string
---------------------
To find the size of a string we use length function member.

string length example 1
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string strName = "This is a string!";

  cout << "Size of the string (using length() function is: " << strName.length() << endl;
  cout << "Size of the string (using size() function) is: " << strName.size() << endl;

  return 0;
}


Check if a string is empty
----------------------------

check if a string is empty in C++
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string strOne;

    if (strOne.empty())
        cout << "String is empty";

    strOne="just a string";
    cout << endl;

    if (!strOne.empty())
        cout << "String is NOT empty";

    return 0;
}



Replacing a character in a string and returning a character at a specified position
-------------------------------------------------------------------------------------------------

See the next example:

Example: replace character at position, return character at a specified position
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string strOne;
  strOne = "This is just a string";

  // we change character at position 18
  strOne[18] = 'X';

  cout << strOne << endl;
  cout << "Character replaced by us is: ";
  cout << strOne[18];
  cout << endl;
  cout << "Character replaced (using at() function) is: ";
  cout << strOne.at(18);

  return 0;

}


Compare two string
-----------------------
We compare two strings with == and != operators.

example for comparing two strings
#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    string strOne = "A string";
    string strTwo = "A string";
    string strThree = "Just another string";
    if ( strOne == strTwo )
        cout << "Strings one and two are identical.";
    else
        cout << "Strings one and two are not the same.";

    cout << endl;

    if (strOne != strThree)
        cout << "String one and three are not identical.";
}


Concatenate or append a string
------------------------------------

We use + to concatenate two strings.
We use += to append two strings.

If you want to append a string and print the output using cout don't forget brackets:

cout << "strings are: " << strOne += strTwo;     // will not compile
cout << "strings are: " << (strOne += strTwo);     // correct

example for concatenating or appending strings in c++
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string strOne = "aaaa";
  string strTwo = "bbb";
  string strThree = strOne + strTwo;
  string strFour = "ccc";

  cout << "strThree: " << strThree;
  cout << endl;

  strFour += strTwo;
  cout << "We append strTwo to strFour." << endl;
  cout << "strFour: " << strFour;
  cout << endl;
}


Search for a pattern in a string
-----------------------------------
To search for a pattern in a string we use find() c++ method.
See the next example:

search for a pattern in a string in C++ using find() function member
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string strOne = "This is a string to test search within a string";
  string key = "search3";
  int position;

  position = strOne.find(key);

  // to check if our search key/sting is contained in our string we
  // compare with string::npos which is returned if we do not find the string.
  if ( position == string::npos ) {
    cout << "Key sting was not found!";
    exit(1);
    }

  cout << "position: " << position;
  cout << endl;

  // we can also start searching from a specified position
  cout << "position: " << strOne.find(key,10);
  cout << endl;
}



Extracting a string from another string
---------------------------------------------

To do that we use substr C++ function member.
The substring that start at position x and is of length y will be copied in a new string.

See example.

extracting a substring from a string using substr C++ function member
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string strOne = "This is just another string.";
  string strTwo;

  // we will extract "just" from strOne string
  strTwo = strOne.substr(8,4);
  cout << "Extracted string is: " << strTwo;
  cout << endl;
}


Inserting a string in another string
----------------------------------------
To insert a string in another string we use C++ insert() function member.


See example:

insert a string in another string with insert() function member
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string strOne = "This is a string";
    string strTwo = "just ";

    strOne.insert(8, strTwo);

    cout << "strOne: " << strOne;
    cout << endl;
}


strOne.insert(8, strTwo) - here we insert strTwo in strOne, at position 8.



Replacing a string within a string
--------------------------------------
To do that we use replace() function member.

replacing a substring within a string
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string strOne = "This is just a string";
    string strTwo = "an example of ";

    strOne.replace(8, 5, strTwo);

    cout << "strOne: " << strOne;
    cout << endl;
}


strOne.replace(8, 5, strTwo); - we remove from strOne from starting position 8, a number of 5 characters  and we add there strTwo string.


Splitting a string
--------------------
Next example shows how to split a string and put values into a vector.

split a string by a key character
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

vector<string> &split_string(const string &str, char key, vector<string> &vect) {
  stringstream sstream(str);
  string element;

  while( getline(sstream, element, key) ) {
    vect.push_back(element);
  }
  return vect;
}

int main(void)
{
  string a="a b c d";
  char key = ' ';
  vector<string> v;

  split_string(a, key, v);
  for (unsigned n=0; n<v.size(); n++) {
    cout << v.at(n) << endl;
  }
}

.

Last Updated ( Friday, 20 May 2011 )
 
< Prev   Next >

Other BSD Systems

OpenBSD

Misc

Solaris

Polls

Best BSD firewall?