String (C++)

String (C++)

In the C++ programming language, the std::string class is a standard representation for a string of text. This class removes many of the problems introduced by C-style strings by putting the onus of memory ownership on the string class rather than on the programmer. This class also provides implicit construction from C-style strings, explicit conversion to C-style strings, and a comparison operator so that strings can be compared using =, !=, <, >, <=, >=, just like integers rather than the cumbersome and error-prone strcmp calls required with C-style strings.

Usage

The std::string class is found in the string header and in the std namespace. So simple usage includes:
#include
#include // For assert().
#include int main() { std::string foo = "hi"; using std::string; // Now we can just say "string". string bar = "hi"; assert(foo = bar); // Strings can be compared with operator =.

std::cout << foo + bar << " "; // Prints "hihi".

return 0;}

Because a string may be stored by value, copying may take as long as "θ"("n") (i.e., copying takes time proportional to the length of the string). (Although GNU and Dinkumware C++ libraries use reference counting and copy-on-write technique to avoid unnecessary copying.) For that reason, strings are generally passed by const reference, as in

void print_the_string(const std::string& str) { std::cout << str;}

Also, because a char* can be implicitly converted to a const std::string& (albeit in "θ"("n") time), this is a convenient type for a function to take. For example:const char* foo = "Hello";std::string bar = "world";print_the_string(foo); // Converts foo to a const std::string.print_the_string(" "); // Converts " " to a const std::string.print_the_string(bar); // Passes bar by const reference.

Operators

The string class is fitted with a number of mathematical and logical operators for ease of use. All operators for the string class have member function equivalents, and all can accept another string or character-string, so operators are purely for appearance and have no other advantage. All, except the assignment operator, can also accept single characters. Most allow the left operand to be a character-string.

The most basic, and obvious, is the assignment operator.string str;str = "abc"; // Assignment operator accepts string literals.str = 'a'; // Invalid -- assignment operator does not accept a char.char* c_str = str; // Invalid -- a character string cannot take the value of a string.

The string class also has a good few options for concatenation.string str1 = "qwe";string str2 = "rty";

string str3;str3 = str1 + str2; // str3 = "qwerty"str3 = "qwe" + str2; // The left operand can be a character-string.

str1 += str2; // str1 = "qwerty"str1 -= str2; // Invalid -- subtraction operations are not supported.

Strings can also be tested for equality and inequality.string str1 = "Banana";string str2 = "Banana";

assert( str1 = str2 );assert( str1 < "banana" ); // True because 'B' comes before 'b' on the ASCII table.

string str3 = "Apple";

assert( str1 > str3 ); // True because 'A' is lower than 'B' on the ASCII table.Also, !=, <=, and >= are valid operations for strings. One advantage of strings over c-strings is that when two c-strings are compared, it is implementation defined as to whether the contents or addresses are compared. Strings, however, always compare by contents and never by address.

Lastly is the random access operator. It allows a string to act as a character-string, returning a reference to a character.string person = "Jakw"; // Should be "Jake".person [3] = 'e';char j = person [0] ;


Wikimedia Foundation. 2010.

Игры ⚽ Нужно сделать НИР?

Look at other dictionaries:

  • String — (str[i^]ng), n. [OE. string, streng, AS. streng; akin to D. streng, G. strang, Icel. strengr, Sw. str[ a]ng, Dan. str[ae]ng; probably from the adj., E. strong (see {Strong}); or perhaps originally meaning, twisted, and akin to E. strangle.] 1. A… …   The Collaborative International Dictionary of English

  • string — [striŋ] n. [ME streng < OE, akin to Ger strang: see STRONG] 1. a) a thin line of twisted fiber used for tying, pulling, fastening, etc.; slender cord or thick thread b) a narrow strip of leather or cloth for fastening shoes, clothing, etc.;… …   English World dictionary

  • STRING — (Search Tool for the Retrieval of Interacting Genes/Proteins) ist eine Bioinformatik Datenbank, die einen umfassenden Überblick über direkte (physikalische) und indirekte (funktionelle) Zusammenhänge und Interaktionen zwischen Proteinen gibt. Sie …   Deutsch Wikipedia

  • string — ► NOUN 1) material consisting of threads twisted together to form a thin length. 2) a piece of such material. 3) a length of catgut or wire on a musical instrument, producing a note by vibration. 4) (strings) the stringed instruments in an… …   English terms dictionary

  • string — [ striŋ ] n. m. • 1977; mot angl. « ficelle » ♦ Anglic. Maillot de bain ou slip très petit, assemblé par des liens, laissant les fesses nues. ⇒ cache sexe. ● string nom masculin (anglais string, corde) Cache sexe qui laisse les fesses nues.… …   Encyclopédie Universelle

  • String — (str[i^]ng), v. t. [imp. {Strung} (str[u^]ng); p. p. {Strung} (R. {Stringed} (str[i^]ngd)); p. pr. & vb. n. {Stringing}.] 1. To furnish with strings; as, to string a violin. [1913 Webster] Has not wise nature strung the legs and feet With firmest …   The Collaborative International Dictionary of English

  • String.h — is the header in the C standard library for the C programming language which contains macro definitions, constants, and declarations of functions and types used not only for string handling but also various memory handling functions; the name is… …   Wikipedia

  • String.h — Demande de traduction string.h → …   Wikipédia en Français

  • String — (engl. string „Schnur“, „Strang“, „Saite“, „Kette“) steht für: Zeichenkette (Informatik); das fundamentale Objekt der Stringtheorie (Physik); kosmischer String, hypothetischer Raumdefekt; String (Kleidung), sehr knappe Höschenform. Die Abkürzung… …   Deutsch Wikipedia

  • String.h — Стандартная библиотека языка программирования С assert.h complex.h ctype.h errno.h fenv.h float.h inttypes.h iso646.h limits.h locale.h math.h setjmp.h signal.h stdarg.h stdbool.h stddef.h stdint.h stdio.h stdlib.h …   Википедия

  • String.h — Saltar a navegación, búsqueda string.h es un archivo de la Biblioteca estándar del lenguaje de programación C que contiene la definición de macros, constantes, funciones y tipos de utilidad para trabajar con cadenas de caracteres y algunas… …   Wikipedia Español

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”