DEV Community

Cover image for Strings in C++
Abhishek Chandra
Abhishek Chandra

Posted on • Updated on

Strings in C++

Youkoso!

Here's Traditional Way (C Language)

  • We use null-terminated (\0) character array, although it is not technically a data type.
  • So, Operators cannot be applied to them, like assignment and comparison operators =, <, >, <=, >=.
// Declaration of character array
char s1[10], s2[10];
s1[10] = "Doge";
Enter fullscreen mode Exit fullscreen mode

s1

// Error Full Code (Don't use at home/work)
s2 = s1;
s2 > s1;
s3 = s1 + s2;
Enter fullscreen mode Exit fullscreen mode

This code results in invalid array operations.

Strings in C++

  • The string class is a expertise class of a more general template called basic_string.
  • Since defining a class in C++ is creating a new data type, string is derived data type.
  • This means operators can be overloaded for this class.

Strings

syntax
class string{
   // Variables
   // functions
   // operators
}

string s1;
s1.function();
s1.operator(arguments);
Enter fullscreen mode Exit fullscreen mode

string operations are safe but time consuming. So, 'char array' (speedy, less operations) concept is not deprecated.

if (speed matters) {
Use character array
}else if (safety and easy manipulation matters) {
Use string class
}

Here's why string is safer than character array

  • Careful programmers like you, can overrun to the end of an array that holds a null terminated (null character \0) string.
  • for example - see below
  • string class handles such issues.
char s3[10];
strcpy(s3,"Hello careful programmers.");
Enter fullscreen mode Exit fullscreen mode

s3

String is also in STL (but concept of string is thought apart from STL concepts)

  • string is an another container class.
  • To use string class, we have to include string header class. (not string.h)

    • #include<string> (for string header class)
    • #include<string.h> (in C, for string functions applied on character array)
String class supports many constructors as follows.
  • string()
  • string(const char *str)
  • string(const string &str)
Operators
  • = (assignment)
  • + (concatenation)
  • += (concatenation assignment)
  • == (equality)
  • != (inequality)
  • < (less than)
  • <= (less than equal to)
  • > (greater than)
  • >= (greater than equal to)
  • [] (subscripting)
  • << (insertion)
  • >> (extraction)
Mixed Operations
  • We can mix string objects with another string object or C style string.
  • C++ string can also be concatenated with character const.
Useful methods
  • assign()
  • append()
  • insert()
  • replace()
  • erase()
  • find()
  • rfind()
  • compare()
  • c_str()
  • size()
Visit :

ittekimasu! :)

Top comments (0)