Sunday, October 18, 2015

c++ string

c++ string

String is like char * in C.
In my opinion, it is easier and safter to use string instead of  char *.
You do not have to worry about memory leak; in C, you need to make sure the length and delete.

Format

std :: string
     -> if you use "using namespace std", you do not need " std:: "

    .length()
        - return word length of string

    .at( "position" )
         - return a string at the postion

    .substring("start point" ,  "length")
        - return sub string of string

    .compare( "compare string")
        - compare two strings. If they are same, it returns 0
 
    + operator
         - add two strings

    .find( "wanted string" )
         - if "wanted string" is in the string, return the first position of the string
         - if there isn't "wanted string", it returns 18446744073709551615 (= string::npos )             

    .erase("start point", "length")
         - erase part of string from starting point until the length

    .replace("position", "length", "replacing string")
         - grab sub string starting at specified postion untill the lenth and repace with the "replacing
            string"
 -------------------------------------------------------------------------------------------------------------------------

The following is practice code. If you have suggestion or correction, please feel free to leave comment.

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char** argv) {

    string input = "hello world";
    string input2 = "hello world";
    string input3 = "hello world2";
   
    //1
    //getting length of string
    int length = input.length();
   
    //2
    //grab a component of string
    for(int i=0; i< length; i++){
        cout << input.at(i) << endl;
    }
    cout << endl;
   
    //3
    //substring start position of 1 upto lenth 5
    string subString = input.substr(1,5);
    cout << subString << endl << endl;

    //4
    // compare two strings are equal, if they are, return 0
    cout << "compare same: " << input.compare(input2) << endl;
    cout << "compare different: " << input.compare(input3) << endl;
    cout << endl;
   
    //5
    // add two string
    cout << "add two strings : " << input + input2 << endl;
   
    //6
    // find string
    cout << "where is lo : " << input.find("lo") << endl << endl;
    cout << "where is z : " << input.find("z") << endl << endl << endl;
  
    //7
    // delete part of string
    input2.erase(0,5);
    cout << "delete position 0 upto length 5 : " << input2 << endl;
   
    //8
    // replace string
    input2.replace(0, 0, "hi");
    cout << "repalce : " << input2 << endl;
   
     return 0;
}

No comments:

Post a Comment