STL之string的使用

// stl_string.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <cstring>
#include <string>
using namespace std;
struct Tets
{
    int val;
    string str;
    Tets() = default;
    Tets(int v, string s)
        : val(v)
        , str(s)
    {}
};

struct podtype
{
    int a;
    char b;

};

/*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Member functions
(constructor)           Construct string object (public member function )
(destructor)            String destructor (public member function )
operator=               String assignment (public member function )
*/


/*
Iterators:
begin       Return iterator to beginning (public member function )
end         Return iterator to end (public member function )
rbegin      Return reverse iterator to reverse beginning (public member function )
rend        Return reverse iterator to reverse end (public member function )
cbegin      Return const_iterator to beginning (public member function )
cend        Return const_iterator to end (public member function )
crbegin     Return const_reverse_iterator to reverse beginning (public member function )
crend       Return const_reverse_iterator to reverse end (public member function )
*/
void constIterator()
{
    const string conStr = "const string";
    for (auto cit = conStr.cbegin(); cit != conStr.cend() ; cit++)
    {
        cout << *cit << ", ";
    }
    cout << endl;
}

/*
Capacity:
size            Return length of string (public member function )
length          Return length of string (public member function )
max_size        Return maximum size of string (public member function )
resize          Resize string (public member function )
capacity        Return size of allocated storage (public member function )
reserve         Request a change in capacity (public member function )
clear           Clear string (public member function )
empty           Test if string is empty (public member function )
shrink_to_fit   Requests the string to reduce its capacity to fit its size.
*/

void capacityTest()
{
    string conStr = "const string";
    cout << "size: " << conStr.size() << endl;     //字符的数量--12
    cout << "sizeof: " << sizeof(conStr) << endl;   //得到的是string类型所占的字节数
    cout << "length: " << conStr.length() << endl;  //字符的数量--12
    cout << "capacity: " << conStr.capacity() << endl;
    cout << "max_size: " << conStr.max_size() << endl;

    /*
    size: 12
    sizeof: 28
    length: 12
    capacity: 15
    max_size: 2147483647
    */

    printf("\n");
    conStr.shrink_to_fit();
    cout << "shrink_to_fit: " << conStr.capacity() << endl;     //shrink_to_fit: 15

    string str1;
    str1.reserve(conStr.size());
    cout << "str1 capacity: " << str1.capacity() << endl;   //str1 capacity: 15
    cout << "str1 size: " << str1.size() << endl;           //str1 size: 0

    //int i = 0;
    //for (auto it = conStr.rend(); it != conStr.rbegin(); it++)
    //{
    //    str1[i] = *it;    //size is 0, so will crash
    //    i++;
    //}
    //cout << "str1 use reserve: " << str1 << endl;

}

void TypeSizeofTest()
{
    cout << "sizeof string: " << sizeof(string) << endl;
    cout << "sizeof char: " << sizeof(char) << endl;
    cout << "sizeof int: " << sizeof(int) << endl;
    cout << "sizeof short: " << sizeof(short) << endl;
    cout << "sizeof long: " << sizeof(long) << endl;
    cout << "sizeof int*: " << sizeof(int*) << endl;

    /*
    sizeof string: 28
    sizeof char: 1
    sizeof int: 4
    sizeof short: 2
    sizeof long: 4
    sizeof int*: 4
    */
}

class simString
{
//using string  = basic_string<char, char_traits<char>, allocator<char>>;

private:
    using _Alty1 = _Rebind_alloc_t<allocator<char>, char>;
    using _Alty_traits1 = allocator_traits<_Alty1>;

    using _Scary_val1 = _String_val<conditional_t<_Is_simple_alloc_v<_Alty1>, _Simple_types<char>,
        _String_iter_types<char, typename _Alty_traits1::size_type, typename _Alty_traits1::difference_type,
        typename _Alty_traits1::pointer, typename _Alty_traits1::const_pointer, char&, const char&>>>;
    using pointer = typename _Alty_traits1::pointer;


private:
    static constexpr auto _BUF_SIZE = _Scary_val1::_BUF_SIZE;
    static constexpr auto _ALLOC_MASK = _Scary_val1::_ALLOC_MASK;
    static constexpr bool _Can_memcpy_val = _Is_specialization_v<char_traits<char>, char_traits> && is_trivial_v<pointer>;
    static constexpr size_t _Memcpy_val_offset = _Size_after_ebco_v<_Container_base>;
    static constexpr size_t _Memcpy_val_size = sizeof(_Scary_val1) - _Memcpy_val_offset;

   /* template <class _Iter>
    using _Is_elem_cptr = bool_constant<_Is_any_of_v<_Iter, const _Elem* const, _Elem* const, const _Elem*, _Elem*>>;*/
};



/*
Element access:
operator[]      Get character of string (public member function )
at              Get character in string (public member function )
back            Access last character (public member function )
front           Access first character (public member function )
*/
void testStringElementAccess()
{
    string str = "this is string";
    cout << "at 5:  " << str.at(5) << endl;
    cout << "back test:  " << str.back() << endl;
    cout << "front test:  " << str.front() << endl;

    /*
    at 5:  i
    back test:  g
    front test:  t
    */
}


/*
Modifiers:
operator+=          Append to string (public member function )
append              Append to string (public member function )
push_back           Append character to string (public member function )
assign              Assign content to string (public member function )
insert              Insert into string (public member function )
erase               Erase characters from string (public member function )
replace             Replace portion of string (public member function )
swap                Swap string values (public member function )
pop_back            Delete last character (public member function )
*/

void stringModifiersTest()
{
    string str1 = "this is string1! ";
    string str2 = "i am boring!";
    cout << "operator + :" << str1 + str2 << endl;
    cout << "string append :" << str1.append(str2) << endl;
    str2.assign("i want change!");
    cout << "after assign str2 is:" << str2 << endl;
    str2.insert(str2.begin(), 'I');
    cout << "after insert str2 is:" << str2 << endl;

    str2.replace(str2.begin(), str2.begin() + 5, str1);
    cout << "after replace str2 is:" << str2 << endl;

    //int i = 0;
    //for (auto it = str2.begin(); it != str2.end(); it++, i++)
    //{
    //    if (i % 2 == 0)
    //    {
    //        str2.erase(it);
    //    }
    //}
    //cout << "after erase str2 is:" << str2 << endl;
}



/*
String operations:
c_str           Get C string equivalent (public member function )
data            Get string data (public member function )
get_allocator   Get allocator (public member function )
copy            Copy sequence of characters from string (public member function )
find            Find content in string (public member function )
rfind           Find last occurrence of content in string (public member function )
find_first_of           Find character in string (public member function )
find_last_of            Find character in string from the end (public member function )
find_first_not_of       Find absence of character in string (public member function )
find_last_not_of        Find non-matching character in string from the end (public member function )
substr                  Generate substring (public member function )
compare                 Compare strings (public member function )
*/

void testStringOperation()
{
    string str1 = "Test string Operations.";
    const char *cstr = str1.c_str();
    const char *cstr1 = str1.data();
    printf("\n\n");
    printf("%s\n%s\n", cstr, cstr1);
    char arr[10]( "char");
    str1.copy(arr, 5);   ///将str1的数据拷贝给arr
    cout << "after copy: " << str1 << endl;

    if (str1.find('O') != std::string::npos)
    {
        cout << "string find test and find!" << endl;
    }
    if (str1.rfind('s') != std::string::npos)
    {
        cout << "string rfind test---->find!" << endl;
    }
    if (str1.find_first_not_of(' '))
    {
        cout << "find_first_not_of ' '" << endl;
    }
    if (str1.find_last_not_of(' '))
    {
        cout << "find_last_not_of ' '" << endl;
    }
    cout << "string substr test: " << str1.substr(10,5) << endl;
    string str2 = "this is string2";
    if (str1.compare(str2))
    {
        cout << "not equal!" << endl;
    }

    auto alloctype = str1.get_allocator();
}



/*
Member constants
npos                            Maximum value for size_t (public static member constant )
    npos是一个静态成员常量,值为size_t的最大可能值,该常量被赋值为-1,而size_t是一个无符号整型,-1是该类型能达到的最大数值。

Non-member function overloads
operator+                       Concatenate strings (function )
relational operators            Relational operators for string (function )
swap                            Exchanges the values of two strings (function )
operator>>                      Extract string from stream (function )
operator<<                      Insert string into stream (function )
getline                         Get line from stream into string (function )


Note:
当 cin 读取数据时,它会传递并忽略任何前导白色空格字符(空格、制表符或换行符)。
一旦它接触到第一个非空格字符即开始阅读,当它读取到下一个空白字符时,它将停止读取。

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
void otherTest()
{
    string str1 = "string1 for swap test.";
    string str2 = "how boring!";
    swap(str1, str2);
    cout << "After swap: " << str1 << "<------------>" << str2 << endl;
    string str3;
    cin >> str3;
    cout << "what i write is: " << str3 << endl;
    string str4;
    getline(cin, str4);
    cout << "test getline: " << str4 << endl;
}


int main()
{
    string str = "This is string";
    char cstr[30];
    memcpy(cstr, str.data(), sizeof(str));   //不安全,越界也不报错,string不是POD类型,不能这么拷贝
    std::cout << cstr << endl;

    //Tets t1;// (100, "struct test");
    //t1.val = 100;
    //t1.str = "another string";
    //Tets t2;
    //memcpy(&t2, &t1, sizeof(Tets));   //can use, but will crash
    //printf("t2 result is: %d , %s\n", t2.val, t2.str.data());
    cout << "Tets is POD:? " << is_pod<Tets>::value << endl;    //0
    cout << "string is POD:? " << is_pod<string>::value << endl;    //0
    cout << "podtype is POD:? " << is_pod<podtype>::value << endl;    //1

    cout << "--------------------string test-----------------------" << endl;
    constIterator();
    printf("\n\n");
    capacityTest();
    printf("\n\n");
    TypeSizeofTest();
    printf("\n----------simulate string --------------------\n");
    cout << "simstring:" << sizeof(simString) << endl;   //string 为啥占28字节???
    printf("\n\n");
    testStringElementAccess();
    stringModifiersTest();
    testStringOperation();
    printf("\n\n");
    otherTest();
}

猜你喜欢

转载自blog.csdn.net/lxiao428/article/details/106716645