String

Introduction

String class is in the standard library (std::string), which lives in the string header.
The string type supports variable-length character strings. Programs that use strings must first include the associated header.

#include <string>
using std::string;

Defining and Initializing strings

Example 1

string s1; Default constructor; s1 is the empty string
string s2(s1); Initialize s2 as a copy of s1
string s3("value"); Initialize s3 as a copy of the string literal
string s4(n, 'c'); Initialize s4 with n copies of the character 'c'

Caution:
Character string literals are not the same type as the standard library string type.

Reading and Writing strings

We can use the iostream and string libraries to allow us to read and write strings using the standard input and output operators:

Example 2

#include <string>
using std::string;
int main()
{
string s; // empty string
cin » s; // read whitespace-separated string into s
cout « s « endl; // write s to the output
return 0;
}

Operations on strings

s.empty() Returns true if s is empty; otherwise returns false
s.size() Returns number of characters in s
s[n] Returns the character at position n in s; positions start at 0.
s1 + s2 Returns a string equal to the concatenation of s1 and s2
s1 = s2 Replaces characters in s1 by a copy of s2
v1 == v2 Returns true if v1 and v2 are equal; false otherwise
{{!=, <, <=,

Adding Character String Literals and strings

When mixing strings and string literals, at least one operand to each + operator must be of string type:

Example 3

     string s1 = "hello";   // no punctuation
     string s2 = "world";
     string s3 = s1 + ", ";           // ok: adding a string and a literal
     string s4 = "hello" + ", ";      // ERROR: no string operand
     string s5 = s1 + ", " + "world"; // ok: each + has string operand
     string s6 = "hello" + ", " + s2; // error: can't add string literals
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.