【C/C++】从API学习 string 库(第2部分)append & push_back & assign & erase & replace & insert

  string 概述

  • String objects are a special type of container, specifically designed to operate with sequences of characters.
  • Unlike traditional c-strings, which are mere sequences of characters in a memory array, C++ string objects belong to a class with many built-in features to operate with strings in a more intuitive way and with some additional useful features common to C++ containers.
  • 字符串对象是一种特殊的容器专门用于操作字符序列
  • 与仅仅是内存数组中的字符序列的传统C字符串不同,c++字符串对象属于这样一个类,它具有许多内置特性,可以以更直观的方式操作字符串,还具有一些c++容器共有的有用特性。

string类成员函数 (Member Functions)

这篇文章是string成员函数的第二部分内容,第一部分请见:

【C/C++】从API出发 学习STL标准模板库 007 string 容器(第1部分)_BigXMeng的博客-CSDN博客

 

目录

string 概述 ​

string类成员函数 (Member Functions)​

5 Element access: 元素访问(存取)

6 string::[Modifiers:] 对字符串的修改

​​string::operator+= 追加内容

​​string::append 追加内容

​​string::push_back(char ch) 追加单个字符

​​string::assign 赋值(用法与append几乎一样 但赋值前 原字符串会被clear())

​​string::erase 删除操作

​​string::replace 替换操作

​string::insert 插入操作


 

 ​ 5 Element access: 元素访问(存取)

声明和验证

const char& operator[] ( size_t pos ); // 返回的是字符的引用对象
const char& at ( size_t pos ); // 返回的是字符的引用对象
/**
 * created by Liu Xianmeng on 2022/12/5
 */
#include <bits/stdc++.h>
using namespace std;
int main(){
    string str ("Test string");
    int i;
    for (i=0; i < str.length(); i++){
        cout << str[i];
        str.at(i) = (char)('A' + i); // 直接对其进行修改
    }
    cout<<endl;
    for (i=0; i < str.length(); i++){
        cout << str[i];
    }
    /* 
        【打印结果】
        Test string
        ABCDEFGHIJK
     */
    return 0;
}

6 string::[Modifiers:] 对字符串的修改

string::operator+= 追加内容

/*
[INSTRUCTION]
Appends a copy of the argument to the string.
The new string content is the content existing in the string object before the call followed by the content of the argument.
The append member function provides a similar functionality with additional options.

[PARAMETERS]
str
    string object. A copy of the content of this object is appended to the object's content.
s
    A pointer to an array containing a null-terminated character sequence (C string), which is appended to the object's content.
c
    Character. This single character is appended to the string object's content.
*/

string& operator+= ( const string& str ); // 可以穿入字符串引用
string& operator+= ( const char* s );     // 可以穿入字符数组名(注意字符数组末尾必须有空字符'\0'结尾)
string& operator+= ( char c );            // 可以穿入单个字符

/**
 * created by Liu Xianmeng on 2022/12/5
 */
#include <bits/stdc++.h>
using namespace std;
int main(){
    string name ("Big");
    string family ("Meng");
    name += " X. ";         // c-string
    name += family;         // string
    name += '!';           // character
    cout << name;
    /* 【打印结果】
        Big X. Meng!
     */
    return 0;
}

string::append 追加内容

string& append ( const string& str ); // 与+=描述一致
string& append ( const string& str, size_t pos, size_t n ); // 从str字符串的pos下标开始追加n个字符
string& append ( const char* s, size_t n ); // 用字符数组的前n个字符进行追加
string& append ( const char* s ); // 与+=描述一致
string& append ( size_t n, char c ); // 用n个c字符进行追加
template <class InputIterator>  // 用其他STL容器进行内容的追加
    string& append ( InputIterator first, InputIterator last );

/**
 * created by Liu Xianmeng on 2022/12/5
 */
#include <bits/stdc++.h>
using namespace std;
int main(){
    string str;
    string str2="Writing ";
    string str3="print 10 and then 5 more";
    // used in the same order as described above:
    str.append(str2);                     // "Writing "
    str.append(str3,6,3);          // "10 "
    str.append("dots are cool",5);       // "dots "
    str.append("here: ");                   // "here: "
    str.append(10,'.');                  // ".........."
    str.append(str3.begin()+8,str3.end());  // " and then 5 more"
    str.append(5,0x2e);                  // "....."
    cout << str << endl;
    /* 【打印结果】
        Writing 10 dots here: .......... and then 5 more.....
     */
    return 0;
}

string::push_back(char ch) 追加单个字符

/**
 * created by Liu Xianmeng on 2022/12/5
 */
#include <bits/stdc++.h>
using namespace std;
int main(){
    string str;
    str.push_back('B'); str.push_back('i');
    str.push_back('g'); str.push_back('X');
    str.push_back('M'); str.push_back('e');
    str.push_back('n'); str.push_back('g');
    cout<<str;
    /* 
       【打印结果】
        BigXMeng
     */
    return 0;
}

​string::assign 赋值(用法与append几乎一样 但赋值前 原字符串会被clear())

string& assign ( const string& str );
string& assign ( const string& str, size_t pos, size_t n );
string& assign ( const char* s, size_t n );
string& assign ( const char* s );
string& assign ( size_t n, char c );
template <class InputIterator>
   string& assign ( InputIterator first, InputIterator last );

/**
 * created by Liu Xianmeng on 2022/12/5
 */
#include <bits/stdc++.h>
using namespace std;
int main(){
    string str;
    string base="The quick brown fox jumps over a lazy dog.";

    str.assign(base);
    cout << str << endl;
    str.assign(base,10,9);
    cout << str << endl;         // "brown fox"
    str.assign("pangrams are cool",7);
    cout << str << endl;         // "pangram"
    str.assign("c-string");
    cout << str << endl;         // "c-string"
    str.assign(10,'*');
    cout << str << endl;         // "**********"
    str.assign(10,0x2D);
    cout << str << endl;         // "----------"
    str.assign(base.begin()+16,base.end()-12);
    cout << str << endl;         // "fox jumps over"

    /* 【打印结果】
        The quick brown fox jumps over a lazy dog.
        brown fox
        pangram
        c-string
        **********
        ----------
        fox jumps over
     */
    return 0;
}

​string::erase 删除操作

【DECALRATION】
string& erase ( size_t pos = 0, size_t n = npos ); // 删除字符从pos开始,删除n个字符iterator erase ( iterator position ); // 删除一个迭代器所指向的字符iterator erase ( iterator first, iterator last ); // 删除迭代器指向的范围字符[first, last)

【INSTRUCTION】
1 Erase characters from string
2 Erases a part of the string content, shortening the length of the string.
3 The characters affected depend on the member function version used:

string& erase ( size_t pos = 0, size_t n = npos );
    Erases a sequence of n characters starting at position pos. Notice that both parameters are optional: with only one argument, the function deletes everything from position pos forwards, and with no arguments, the function deletes the entire string, like member clear.iterator erase ( iterator position );
    Erases the character referred by the iterator position. Only one character is affected.iterator erase ( iterator first, iterator last );
    Erases all the characters between first and last.

【PARAMETERS EXPLANITION】
[pos]
    Position within the string of the first character to be erased.
    If the position passed is past the end of the string, an out_of_range exception is thrown.
[n]
    Amount of characters to be removed. It may remove less characters if the end of the string is reached before the n characters have been erased. The default value of npos indicates that all the characters until the end of the string should be erased.
    size_t is an unsigned integral type.

[position]
    Iterator of the member type string::iterator referring to a single character in the string to be removed.

[first]
    Iterator of the member type string::iterator referring to the first character in a sequence of characters within the string to be erased.

[last]
    Iterator of the member type string::iterator referring to the last character in the sequence of characters within the string to be erased.


【RRTURN VALUE】
For the member that returns a string&, the function returns *this.
For the remaining members, the function returns an iterator of member type string::iterator referring to the character that now occupies the position of the first character erased, or, if no such character exists, returns end().
【DEMONSTRATION】
/**
 * created by Liu Xianmeng on 2022/12/5
 */
#include <bits/stdc++.h>
using namespace std;
int main(){
    string str ("1234 56 78 9ABCDEF GHIJKL.");
    string::iterator it;

    str.erase (10,8); // 从下标为10的字符连续删除8个字符("9ABCDEF ")
    cout << str << endl;        // 1234 56 78 GHIJKL.
    it=str.begin()+9;
    str.erase (it); // 删除字符'8'
    cout << str << endl;        // 1234 56 7 GHIJKL.
    // 从第六个字符开始,删除到end()-7 ("56 7 ")
    str.erase (str.begin()+5, str.end()-7);
    cout << str << endl;        // 1234 GHIJKL.
    /* 
        【打印结果】
        1234 56 78 GHIJKL.
        1234 56 7 GHIJKL.
        1234 GHIJKL.
     */
    return 0;
}

string::replace 替换操作

[DECLARATION] 猜一下 各自有什么功能?

string& replace ( size_t pos1, size_t n1,   const string& str ); // 将原字符串下标从pos1开始的n1个字符替换为str
string& replace ( iterator i1, iterator i2, const string& str ); // 将原字符串[i1, i2)范围的字符替换为str

// 将原字符串下标从pos1开始的n1个字符替换为:str从pos2下标开始的n2个字符
string& replace ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 );

string& replace ( size_t pos1, size_t n1,   const char* s, size_t n2 ); // s[前n2]->原str[pos1, pos1+n1)
string& replace ( iterator i1, iterator i2, const char* s, size_t n2 ); // s[前n2]->原str[i1, i2)

string& replace ( size_t pos1, size_t n1,   const char* s ); // s->原[pos1, pos1+n1)
string& replace ( iterator i1, iterator i2, const char* s ); // s->原[i1, i2)

string& replace ( size_t pos1, size_t n1,   size_t n2, char c ); // c,n2个 -> 原[pos1, pos1+n1) 
string& replace ( iterator i1, iterator i2, size_t n2, char c ); // c,n2个 -> 原[i1, i2)

template<class InputIterator> // 其他容器[j1, j2) -> 原[i1, i2)
   string& replace ( iterator i1, iterator i2, InputIterator j1, InputIterator j2 );

[DEMONSTRATION]
/**
 * created by Liu Xianmeng on 2022/12/5
 */
#include <bits/stdc++.h>
using namespace std;
int main(){
    string base="this is a test string.";
    string str2="n example";
    string str3="sample phrase";
    string str4="useful.";
    
    // Using positions:
    string str=base;                // "this is a test string."
    // "n example" ->替换 " test"
    str.replace(9,5,str2);          // "this is an example string."
    // "phrase" ->替换 "string"
    str.replace(19,6,str3,7,6);     // "this is an example phrase."
    // "just a" ->替换 "an example"
    str.replace(8,10,"just all",6); // "this is just a phrase."
    // "a short" ->替换 "just a"
    str.replace(8,6,"a short");     // "this is a short phrase."
    // "." 替换为 3*"!"
    str.replace(22,1,3,'!');        // "this is a short phrase!!!"
    
    // Using iterators:           
    string::iterator it = str.begin();  
    // str3 ->替换 "this is a short phrase"
    str.replace(it,str.end()-3,str3);    // "sample phrase!!!"
    // "replace" -> "sample"
    str.replace(it,it+6,"replace it",7); // "replace phrase!!!"
    it+=8;             
    // "is cool" -> "phrase"
    str.replace(it,it+6,"is cool");      // "replace is cool!!!"
    str.replace(it+4,str.end()-4,4,'o'); // "replace is cooool!!!"
    it+=3;    
    // "useful." -> "cooool!!!"
    str.replace(it,str.end(),str4.begin(),str4.end()); // "replace is useful."
    cout << str << endl; // "replace is useful."
    return 0;
}

string::insert 插入操作

[DECLARATION]

string& insert ( size_t pos1, const string& str ); // 在下标pos1出插入str

// str[pos2,pos2+n) -> 原str[pos1]
string& insert ( size_t pos1, const string& str, size_t pos2, size_t n );

string& insert ( size_t pos1, const char* s, size_t n); // s[前n chs] -> 原str[pos1]

string& insert ( size_t pos1, const char* s ); // s -> 原str[pos1]

string& insert ( size_t pos1, size_t n, char c ); // c*n -> 原str[pos1]

iterator insert ( iterator p, char c ); // c -> *p; return p;

void insert ( iterator p, size_t n, char c ); // c*n -> *p; return p;

template<class InputIterator> // 某容器[first, last) -> *p
    void insert ( iterator p, InputIterator first, InputIterator last );

void swap ( string& str ); // 就是纯粹地交换两个字符串的内容


/**
 * created by Liu Xianmeng on 2022/12/5
 */
#include <bits/stdc++.h>
using namespace std;
int main(){
    string buyer ("money");
    string seller ("goods");
    cout << "Before swap, buyer = " << buyer;
    cout << " ; seller = " << seller << endl;
    seller.swap (buyer);
    cout << " After swap, buyer = " << buyer;
    cout << " ; seller = " << seller << endl;
    /* 【打印结果】
        Before swap, buyer = money ; seller = goods
        After swap, buyer = goods ; seller = money
     */
    return 0;
}

(后续更新..)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值