2.1.1. Further operations on strings

Let us have a look at some further basic operations of the class string. We create a string, access parts of it and replace them by other strings or completely delete them. Finally, we concatenate a couple of strings.

Filename: StringBasics.C
LEDA users as of version 5.0: Note that header files are now partitioned into modules (subfolders)!
#include <LEDA/string.h>
#include <iostream>

using leda::string;
using std::cout;
using std::endl;

int main()
{
  string s = "The LEDA Tutorial"; // LEDA rule 1

  cout << s.head(3) << endl; 
  cout << s(4,8) << endl;    // substring
  cout << s.tail(8) << endl; 

  string t("LEDA"); // equivalent to t = "LEDA";

  cout << "LEDA is a substring starting on position " << s.pos(t) << endl;

  s = s.insert("wonderful ",4); 
  cout << s << endl;
  
  s = s.replace("LEDA Tutorial","soupstone");
  cout << s << endl;

  s = s.replace_all("soupstone","soupstone by Dr. Hook");
  cout << s << endl;

  s = s.del("soupstone by ");
  cout << s << endl;

  string u;
  u = s;  // let u and s reference the same memory
  u = u + " sings '" + t + " " + t + " " + t +"'" ;
  cout << u << endl;
}

The output of the program is

The
LEDA
Tutorial
LEDA is a substring starting on position 4
The wonderful LEDA Tutorial
The wonderful soupstone
The wonderful soupstone by Dr. Hook
The wonderful Dr. Hook
The wonderful Dr. Hook sings 'LEDA LEDA LEDA'

The method

s.pos(t);

searches in a string s for the substring t and returns the position at which t occurs for the first time in s and -1 if the substring t does not occur, respectively. The count starts at 0, that is, the first character of a string s is the character s[0].

The methods

s.head(i);
s.tail(i);

return the first and the last i characters, respectively, of the string s (in a new object of type string).

With the overloaded function operator

s(n,m);

the substring starting from the character at position n (exclusively) and ending with the character at position m (inclusively) can be extracted.

The method

s.insert(i, t);

inserts a string t at position i into s.

The method

s.replace(t, u);

replaces the fist occurrence of the substring t by the string u.

In contrast,

s.replace_all(t, u);

replaces all occurrences of t by u.

By

s.del(t);

the first occurrence of t in s deleted, that is, it is replaced by the empty string.

The operator

s + t;

concatenates two strings, that is, it returns a string that consists of all characters of s followed by all characters of t.

Finally, the assignment operator

s = t;

assigns a copy of the string t to a string s.

In this process none of these methods and operators changes the original string; in every case a modified string is returned.




Imprint-Dataprotection