Skip to main content

CPP string Class

C++ Standard Library: The string Class

The string class is part of the C++ standard library. A string represents a sequence of characters.
To use the string class, #include the header file:
    #include <string>

Constructors:

  • string ()
    - creates an empty string ("")
  • string ( other_string )
    - creates a string identical to other_string
  • string ( other_string, position, count )
    - creates a string that contains count characters from other_string, starting at position. If count is missing (only the first two arguments are given), all the characters from other_string, starting at positionand going to the end of other_string, are included in the new string.
  • string ( count, character )
    - create a string containing character repeated count times
Examples:
 string s1;                //   s1 = ""                

 string s2( "abcdef" );    //   s2 = "abcdef"          

 string s3( s2 );          //   s3 = "abcdef"          

 string s4( s2, 1 );       //   s4 = "bcdef"           

 string s5( s2, 3, 2 );    //   s5 = "de"              

 string s6( 10, '-' );     //   s6 = "----------"      

      
The string class also has a destructor that takes care of freeing the memory storing the characters when the object is destroyed.

Constant Member Functions:

These functions do not modify the string.
  • const char * data ()
    - returns a C-style null-terminated string of characters representing the contents of the string
  • unsigned int length ()
    - returns the length of the string
  • unsigned int size ()
    - returns the length of the string (i.e., same as the length function)
  • bool empty ()
    - returns true if the string is empty, false otherwise

Operators Defined for string:

  • Assign =
    string s1;
    string s2;
    ...
    s1 = s2; // the contents of s2 is copied to s1
  • Append +=
    string s1( "abc" );
    string s2( "def" );
    ...
    s1 += s2; // s1 = "abcdef" now
  • Indexing []
    string s( "def" );
    char c = s[2]; // c = 'f' now
    s[0] = s[1]; // s = "eef" now
  • Concatenate +
    string s1( "abc" );
    string s2( "def" );
    string s3;
    ...
    s3 = s1 + s2; // s3 = "abcdef" now
  • Equality ==
    string s1( "abc" );
    string s2( "def" );
    string s3( "abc" );
    ...
    bool flag1 = ( s1 == s2 ); // flag1 = false now
    bool flag2 = ( s1 == s3 ); // flag2 = true now
  • Inequality !=
    - the inverse of equality
  • Comparison <, >, <=, >=
    - performs case-insensitive comparison
    string s1 = "abc";
    string s2 = "ABC";
    string s3 = "abcdef";
    ...
    bool flag1 = ( s1 < s2 ); // flag1 = false now
    bool flag2 = ( s2 < s3 ); // flag2 = true now

Member Functions:

  • void swap ( other_string )
    - swaps the contents of this string with the contents of other_string.
    string s1( "abc" );
    string s2( "def" );
    s1.swap( s2 ); // s1 = "def", s2 = "abc" now 

  • string & append ( other_string )
    - appends other_string to this string, and returns a reference to the result string.
  • string & insert ( position, other_string )
    - inserts other_string into this string at the given position, and returns a reference to the result string.
  • string & erase ( position, count )
    - removes count characters from this string, starting with the character at the given position. If count is ommitted (only one argument is given), the characters up to the end of the string are removed. If bothposition and count are omitted (no arguments are given), the string is cleared (it becomes the empty string). A reference to the result string is returned.
  • unsigned int find ( other_string, position )
    - finds other_string inside this string and returns its position. If position is given, the search starts there in this string, otherwise it starts at the beginning of this string.
  • string substr ( position, count )
    - returns the substring starting at position and of length count from this string








#include <cstring>

#include <algorithm>
using namespace std;

int main() {

    // INITIALIZATION

    string a;   // Empty string
    string b("Quora");
    string c = "Quora";
    string d = b;
    string e(c);

    // INITIALIZING WITH C-STYLE STRING
    char str[10] = "Quora";
    string f = str;
    string g(str);


    // CHECK STRING IS EMPTY OR NOT
    if (a.empty())
        cout << "Empty string\n";


    // FIND LENGTH OF STRING
    int bLen = b.length();
    // cout << bLen << endl;


    // CONCATENATION OF STRING
    string abc = b + d;

    // Note : For concatenation to work, atleast one of them must be <string> type
    // string tN = "Does" + "not" + "work"  // compile time error
    
    string tY = string("This") + "will" + "work";
    // tY = "This will work"

    
    
    // FIND A SUBSTRING

    // string.find() -> finds first occurence
    // string.rfind() -> finds last occurence

    int found = tY.find("will");

    if (found == -1)
        cout << "Not Found\n";
    else
        cout << "Found at index : " << found << endl;



    // MAKE THE STRING EMPTY
    // tY.clear();


    // ERASE ANY SUBSTRING 
    // string.erase(index, length)

    tY.erase(05);
    // cout << tY << endl;


    // STRING TO SUBSTRING
    // string.substr(index, length)

    string subString = b.substr(13);
    // cout << subString << endl;



    // INSERT A STRING 
    // string.insert(index, string)

    tY.insert(0"Quora "); // inserts at beginning 
    // cout << tY << endl;    


    // COMPARE STRINGS
    // all relational operator work on string
    //  ==  !=  >  <  >=  <=  

    if (== c)
        cout << "Equal strings\n";

    // Alternatively
    // s1.compare(s2) 



    // Compatibility of <string> with C-style string

    /********* string.c_str()  behaves as C-style string *******/

    int len = strlen(tY.c_str());
    cout << len << endl; 
    
    string number = "12345";
    int num = atoi(number.c_str());
    cout << num << endl;

  
    // Whenever char * is required rather than const char * USE
    // const_cast<char *> (string.c_str())
  
    // Splitting a string based on a tokenizer
    // strtok(char *, const char *)
     
     string sentence = "Today is Monday 29-07-14";
     char *= strtok(const_cast<char *>(sentence.c_str())" ");
     while (!= NULL) {
          cout << p << endl;
          p = strtok(NULL" ");
     }

    return 0;
}



 stdout
Empty string
Found at index : 4
Equal strings
13
12345
Today
is
Monday
29-07-14

Comments

Popular posts from this blog

C Questions

C Questions
C Questions

Note : All the programs are tested under Turbo C/C++ compilers.
It is assumed that,
Programs run under DOS environment, The underlying machine is an x86 system, Program is compiled using Turbo C/C++ compiler.
The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed).
Predict the output or error(s) for the following:

void main()
{
int const * p=5; printf("%d",++(*p));
}
Answer:
Compiler error: Cannot modify a constant value.
Explanation:
p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".
main()
{
char s[ ]="man"; int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer: mmmm
aaaa nnnn
Explanation

Zoho Interview | Set 1 (Advanced Programming Round)

Third Round: (Advanced Programming Round) Here they asked us to create a “Railway reservation system” and gave us 4 modules. The modules were:
    1. Booking
    2. Availability checking
    3. Cancellation
    4. Prepare chart
We were asked to create the modules for representing each data first and to continue with the implementation phase.

 My Solution :

#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<string.h>#include<iostream.h>#include<time.h>#include<iomanip.h>#include<fstream.h>char f[10]="f";char s[10]="s";int addr,ad,flag,f1,d,m,i,amt;float tamt; class login {public:char id[100];char pass[100];char*password;void getid(){ cout<<"Enter your id:";gets(id); password=getpass("Enter the password:");strcpy(pass,password);}void displayid(){ cout<<"Id:";puts(id); cout<<"Password:";puts(pass);}}; class detail {public:in…

Hackerrank > SQL > Basic Select

Select
01-Select All
Given a City table, whose fields are described as +-------------+----------+ | Field       | Type     | +-------------+----------+ | ID          | int(11)  | | Name        | char(35) | | CountryCode | char(3)  | | District    | char(20) | | Population  | int(11)  | +-------------+----------+
write a query that will fetch all columns for every row in the table.

My Solution
SELECT*FROM city;
---------------------------------------------------------------------------------
02-Select by ID
Given a City table, whose fields are described as