c++ string STl 标准模板库(待完善)

String STl

1.构造函数

string类的构造函数,参考C++primeplus第六版

构 造 函 数 描 述
string(const char * s) 将string对象初始化为s指向的NBTS
string(size_type n, char c) 创建一个包含n个元素的string对象,其中每个元素都被初始化为字符c
string(const string & str) 将一个string对象初始化为string对象str(复制构造函数)
string( ) 创建一个默认的sting对象,长度为0(默认构造函数)
string(const char * s, size_type n) 将string对象初始化为s指向的NBTS的前n个字符,即使超过了NBTS结尾
template<class Iter> string(Iter begin, Iter end) 将string对象初始化为区间[begin, end)内的字符,其中begin和end的行为就像指针,用于指定位置,范围包括begin在内,但不包括end
string(const string & str, string size_type pos = 0, size_type n = npos) 将一个string对象初始化为对象str中从位置pos开始到结尾的字符,或从位置pos开始的n个字符
string(string && str) noexcept 这是C++11新增的,它将一个string对象初始化为string对象str,并可能修改str(移动构造函数)
string(initializer_list<char> il) 这是C++11新增的,它将一个string对象初始化为初始化列表il中的字符

示例:

#include <iostream>
#include <string>

int main()
{
    using namespace std;
    //使用char*字符串构造
    string one("Lottery Winner!");
    cout << one << endl;
    //构造含有n个字符的字符串
    string two(20, '$');
    cout << two << endl;
    //复制构造
    string three(one);
    cout << three << endl;
    //运算符重载
    one += " Oops!";
    cout << one << endl;
    two = "Sorry! That was ";
    //按位赋值
    three[0] = 'P';
    string four;
    four = two + three;
    cout << four << endl;
    char alls[] = "All's well that ends well";
    //使用一个char*字符串的前几位构造,可以超出源字符串范围
    string five(alls, 20);
    cout << five << "!\n";
    //使用迭代器构造
    string six(alls + 6, alls + 10);
    cout << six << ",";
    string seven(&five[6], &five[10]);
    cout << seven << "...\n";
    //使用字符串中的某位的开端到某位的开端
    string eight(four, 7, 16);
    cout << eight << " in motion!" << endl;
    return 0;
}

输出:

Lottery Winner!
$$$$$$$$$$$$$$$$$$$$
Lottery Winner!
Lottery Winner! Oops!
Sorry! That was Pottery Winner!
All's well that ends!
well,well...
That was Pottery in motion!

2.迭代器

Iterators: 描述
begin 提供正向迭代器支持
end 提供正向迭代器支持
rbegin 提供逆向迭代器支持
rend 提供逆向迭代器支持
cbegin 提供const迭代器支持
cend 提供const迭代器支持
crbegin 提供const逆向迭代器支持

示例:

#include <iostream>
#include <string>

int main()
{
    using namespace std;
    string one("Lottery Winner!");
    string::const_iterator ptr = one.cbegin();
    string two(one.begin(), one.begin() + 9);
    string three(one.end() - 9, one.end());
    string four(one.rbegin(), one.rend());
    cout << *ptr << endl;
    *one.begin() = 'l';
    cout << "one:" << one << endl;
    cout << "two: " << two << endl;
    cout << "three: " << three << endl;
    cout << "four: " << four << endl;
    return 0;
}

输出:

L
one:lottery Winner!
two: Lottery 
three: y Winner!
four: !renniW yrettoL

3.容量相关:

Capacity: 描述
size 返回字符串长度
length 返回字符串长度,等同于length
max_size 返回字符的最大可能个数
resize 改变字符数量
capacity 返回当前分配给字符串的存储空间的大小,以字节表示。此容量不一定等于字符串长度。
reserve 将字符串容量调整为为长度至n字符。
clear 清空字符串
empty 判断字符串是否为空
shrink_to_fit 自适应字符串容量

示例:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str(10, 'x');
    //这个大小和电脑内存有关
    cout << "max size:" << str.max_size() << endl;
    // length() 等同于 size()
    cout << "1. capacity of str: " << str.capacity() << " size of str:" << str.size() << '\n';

    /*
     * void resize (size_t n);
     * void resize (size_t n, char c);
     将字符串调整为n字符的长度。
     如果 n 比当前字符串长度小,则当前值将缩短为其第一个 n 字符,删除 n th 以外的字符。
     如果 n 大于当前字符串长度,则当前内容通过在末端插入尽可能多的字符来扩展,以达到 n 的大小。
     如果c被指定,则新元素将初始化为c的副本,否则,它们是价值初始化字符(空字符)。
    */
    str.resize(5, ' ');
    cout << "after resize:" << str << endl;
    str.resize(10, 's');
    cout << "resize again:" << str << endl;
    cout << "2. capacity of str: " << str.capacity() << " size of str:" << str.size() << '\n';

    /*
     * void reserve (size_t n = 0);
     将字符串容量capacity为n字符。
     如果 n 大于当前字符串容量,则函数会导致容器将容量增加到 n 字符(或更大)。
     如果小于则保持原有capacity
     此功能对字符串长度没有影响,不能更改其内容。
    */
    str.reserve(20);
    cout << "3. capacity of str: " << str.capacity() << " size of str:" << str.size() << '\n';

    /*
     * void shrink_to_fit();
     自适应修改capacity的大小
     此功能对字符串没有影响,不能更改其内容。
    */
    str.shrink_to_fit();
    cout << "4. capacity of str: " << str.capacity() << " size of str:" << str.size() << '\n';

    /*
     *void clear();
     擦除字符串的内容,使该字符串变为空字符串(长度为0个字符)。
     *bool empty() const;
     如果字符串长度是0则返回true,否则返回false。
    */
    str.clear();
    if (str.empty())
        cout << "string is empty." << endl;
    else
        cout << str;
    return 0;
}

输出:

不同编译器结果不同,但是功能相同

max size:9223372036854775807
1. capacity of str: 15 size of str:10
after resize:xxxxx
resize again:xxxxxsssss
2. capacity of str: 15 size of str:10
3. capacity of str: 30 size of str:10
4. capacity of str: 15 size of str:10
string is empty.

4.访问元素:

Element access:
运算符[ ] 以下标存取单一字符
at 以下标存取单一字符
back 获取末尾的字符
front 获取开头的字符

示例:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str("hello world.");
    cout << "original string:" << str << endl;
    str.front() = 'H';
    str.back() = '!';
    cout << str << '\n';
    for(auto i :str)
        cout<<i<<" ";
    cout<<endl;
    cout<<str.at(1);
    cout<<str[2];
    return 0;
}

输出:

original string:hello world.
Hello world!
H e l l o   w o r l d !
el

5.修改字符串:

Modifiers: 描述
[运算符]+= 在末尾增加字符串
append 在末尾增加字符串
push_back 在末尾增加单个字符
assign 给一部分赋值
insert 插入字符
erase 删除字符
replace 替换字符
swap 交换两个字符串的内容
pop_back 删除末尾字符

示例:

这个部分重载太多了,就不全部列出了,可以直接点上面的链接,官网的例程很详细.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str("hello");
    cout<<"str:"<<str<<endl;
    str+=" ";
    cout<<"str:"<<str<<endl;
    str.append("world");
    cout<<"str:"<<str<<endl;
    str.push_back('.');
    cout<<"str:"<<str<<endl;
    str.replace(0,1,"H");
    cout<<"str:"<<str<<endl;
    str.insert(5,",");
    cout<<"str:"<<str<<endl;
    str.assign(2,'H');
    cout<<"str:"<<str<<endl;
    return 0;
}

输出:

str:hello
str:hello
str:hello world
str:hello world.
str:Hello world.
str:Hello, world.
str:HH

6.字符串处理:

String operations:
c_str 将内容以 C - string 形式返回
data 将内容以字符数组形式返回
get_allocator 返回和对象相关的分配器的一个拷贝
copy 将内容复制为一个 C - string
find 正向搜寻第一次出现的某子字符串或字符
rfind 反向搜寻第一次出现的某子字符串或字符
find_first_of 寻找单字符在字符串中的第一个下标
find_last_of 寻找单字符在字符串中的最后一个下标
find_first_not_of 寻找单字符在字符串中缺失后的第一个下标
find_last_not_of 寻找单字符在字符串中缺失后的第一个下标
substr 返回子字符串
compare 比较字符串内容

find函数:

方 法 原 型 描 述
size_type find(const string & str, size_type pos = 0)const 从字符串的pos位置开始,查找子字符串str。如果找到,则返回该子字符串首次出现时其首字符的索引;否则,返回string :: npos
size_type find(const char * s, size_type pos = 0)const 从字符串的pos位置开始,查找子字符串s。如果找到,则返回该子字符串首次出现时其首字符的索引;否则,返回string :: npos
size_type find(const char * s, size_type pos = 0, size_type n) 从字符串的pos位置开始,查找s的前n个字符组成的子字符串。如果找到,则返回该子字符串首次出现时其首字符的索引;否则,返回string :: npos
size_type find(char ch, size_type pos = 0)const 从字符串的pos位置开始,查找字符ch。如果找到,则返回该字符首次出现的位置;否则,返回string :: npos

示例:

// string::back
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main()
{
    string str("Hello, world!");
    string str1("hello, world!");
    //data()和c_str()的返回是const char*类型
    char *s1 = new char[str.length() + 1];
    strcpy(s1, str.c_str());
    char const *s2 = str.data();
    char s3[20];
    std::size_t length = str.copy(s3, 5, 7);
    s3[length] = '\0';
    string s4 = str.substr(0, 5);
    cout << "s1:" << s1 << endl;
    cout << "s2:" << s2 << endl;
    cout << "s3:" << s3 << endl;
    cout << "s4:" << s4 << endl;
    delete[] s1;

    if (str.find('H') != string::npos)
        cout << "str contains 'H'" << endl;
    else
        cout << "str doesn't contain 'H'" << endl;

    if (str.compare(str1) != 0)
        cout << str << " is not " << str1 << '\n';
    else
        cout << str << " is the same as" << str1 << '\n';

    return 0;
}

输出:

s1:Hello, world!
s2:Hello, world!
s3:world
s4:Hello
str contains 'H'
Hello, world! is not hello, world!

7.全局变量

Member constants
npos Maximum value for size_t (public static member constant )

最大值:18446744073709551615

通常用于比较字符串

示例:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    cout <<string::npos;
    return 0;
}

输出:

18446744073709551615

8.非成员函数的重载

Non-member function overloads
运算符+ 连接两个字符串
关系运算符 ==, !=, <, <=, >, >= 按照ascII码值比较字符串的每一位; 如果直到某个字符串结束都相等,长的大; 也可以用compare
swap 交换两个字符串的内容
运算符>> 从流中提取字符串 ,例如cin>>
运算符<< 将字符串插入流中,例如cout<<
getline Get line from stream into string (function )

示例:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    string admin("admin");
    cout << "Please, enter your full name:";
    getline(cin, name);
    cout << "Hello, " << name << "!\n";
    swap(admin,name);
    cout << "Now you are " << name << "!\n";
    return 0;
}

输出:

Please, enter your full name:leo
Hello, leo!
Now you are admin!

9.转换函数

Convert from strings
stoi int
stol long int
stoul unsigned int
stoll long long
stoull unsigned long long
stof float
stod double
stold long double

注意,只能转换字符串,不能转换单字符

示例:

#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

using namespace std;

int main ()
{
    string num1("-123.456");
    string num2("789");
    cout<<stoi(num1)<<endl;
    cout<<stol(num1)<<endl;
    cout<<stoul(num2)<<endl;
    cout<<stoll(num1)<<endl;
    cout<<stoull(num2)<<endl;
    cout<<stof(num1)<<endl;
    cout<<stod(num1)<<endl;
    cout<<stold(num1)<<endl;
    return 0;
}

输出:

-123
-123
789
-123
789
-123.456
-123.456
-123.456

参考:

http://c.biancheng.net/view/1441.html

https://www.cplusplus.com/reference/string/string/?kw=string

c++ prime plus 第16章

posted @ 2021-11-02 23:08  李柳星  阅读(64)  评论(0编辑  收藏  举报