C++中 string 中的方法的使用詳解(心得)


string 字符串在所有的語言中都非常重要,c++也不例外,接下來我們將介紹string中的常用方法

1. size() 和 length() 函數 : 他們返回字符串的真實長度,且不會因為空格而截斷,這兩個方法完全等價,使用及輸出如下:

#include<iostream>
#include<string>
using namespace std;
 
int main(void)
{
    string s = "dasddasd";
    printf("size()返回的長度為:%lu\nlength()返回的長度為:%lu",s.size(),s.length());
    return 0;
}

 

2. find()函數和rfind()函數 : 這兩個函數用於查找字串在母串中的位置,並且返回該位置,當然如果找不到就會返回一個特別的標記string::nops,而find()函數是從字符串開始指針向后進行查找,rfind()函數是從字符串的結束指針開始向前查找,其使用及輸出如下:

 

#include<iostream>
#include<string>
using namespace std;

int main(void)
{
    string s = "hello worldh";
    int index = s.find("h");     // 從串首向后查找
    int index2 = s.find("h",2)   // 固定位置后子串在母串的位置
    int index1 = s.rfind("h");  // 從串尾向前查找
    printf("(find()):字母h在母串中的位置為:%d\n", index); 
    printf("(rfind()):字母h在母串中的位置為:%d", index1);
    return 0;
}

值得注意的是我們可以通過組合使用這兩個函數來實現判斷該子串是否唯一存在於母串中,其實現代碼如下:

#include<iostream>
#include<string>
using namespace std;

inline bool whetherOnly(string &str,string &base){
    return base.find(str) == base.rfind(str); 
}

 

3. find_last_of()函數和find_first_of()函數:從函數名我們也可以知道find_last_of()函數是找這個子串在母串中最后一次出現的位置並且將該位置返回;而find_first_of()函數是找這個子串在母串中最后一次出現的位置並將該位置返回,其使用及輸出如下:

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    string s = "hello worldh";
  
    int index = s.find_first_of("h");
    int index1 = s.find_last_of("h");
    printf("(find_first_of()):字母h在母串中的位置為:%d\n", index);
    printf("(find_last_of()):字母h在母串中的位置為:%d", index1);
}

 

 

4.assign()函數:該函數用於將目標串的值復制到該串上,並且只復制值,其使用及輸出如下:

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    string s = "hello worldh";
    s.clear();
    s.assign("hello world");
    cout<<s<<endl;
    
}

 

5.clear()函數,把當前字符串清空,這時候如果調用string::size()函數或string::length()函數將返回0,其使用及輸出如下:

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    string s = "hello worldh";
    s.clear();
    cout<<"clear后的串的長度"<<s.size()<<endl;
}

 

6.resize()函數,該函數可以將字符串變長到指定長度,若小於原本字符串的長度,則會截斷原字符串;這個函數的一個重載形式是str.resize(length,'s') 可以用該輸入字符's'來對字符串進行擴充至length的長度,該函數的使用及輸出如下:

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    string s = "hello worldh";
    s.resize(5);       // s會變為 hello
    cout<<s<<endl;
    s.resize(10,'C'); // s 會變為 helloCCCCC
    cout<<s<<endl;
    
}

 

7. replace(pos,len,dist)函數: 該函數用於將該串從pos位置開始將長度為len的字串替換為dist串,值得注意的是該函數只替換一次,這與市面上的py和java等語言不一樣,需要留意,該函數的使用和輸出如下:

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    string s = "hello worldh";
    s.replace(s.find("h"),2,"#"); // 把從第一個h開始的兩個字符變為一個字符 #
    cout<<"替換后的字符串為: "<<s<<endl;
    
}

那么既然C++本身不提供,替換所有子串的函數,我們就自己實現一個,其代碼如下:

// 替換字符串里的所有指定字符
string replace(string &base, string src, string dst) //base為原字符串,src為被替換的子串,dst為新的子串
{
    int pos = 0, srclen = src.size(), dstlen = dst.size();
    while ((pos = base.find(src, pos)) != string::npos)  
    {
        base.replace(pos, srclen, dst);
        pos += dstlen;
    }
    return base;
}

8. erase(index,length)函數:該函數刪除index位置后length長度的子串,其代碼及輸出如下:

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    string s = "hello worldh";
    s.erase(s.find("h"),3);
    cout<<"擦除過后的串"<<s<<endl; // 將會輸出lo worldh
}

 

9.substr(index,length)函數:該函數從index開始截斷到長度為length並返回截斷的子串;值得注意的是,該函數不改變母串的值,其使用及輸出如下:

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    s = s.substr(0,5); 
    cout<<"截斷並賦值后的字符串為:"<<s<<endl; // 會輸出hello
}

 

10 . push_back(char c)函數,pop_back()函數,append(string s)函數:push_back(char c)函數往該字符串的尾端加入一個字符;pop_back()函數從該字符串的尾端彈出一個字符;而apend(string s)函數將會在該字符串的末尾添加一個字符串,並且返回添加后字符串的引用。他們的使用及輸出如下圖所示:

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    string s = "hello worldh";
    // s.erase(s.find("h"),3);
    s.pop_back(); //彈出串的最后一個元素
    cout<<"彈出串尾元素后的字符串為: "<<s<<endl;
    s.push_back('s'); // 在串的最后添加一個字符
    cout<<"往串尾添加字符后的字符串為: "<<s<<endl;
    s.append("hhh"); // 在串的最后添加一個字符串
    cout<<"往串尾添加字符串后的字符串為: "<<s<<endl;
}

 

以上就是string中比較重要的函數的全部內容了,既然我們學完了該內容,那我們接下來做一條題來熟悉一下這些函數中的一些吧(題目與代碼如下代碼塊,題目出自leetcode):

 1 // 給你一份『詞匯表』(字符串數組) words 和一張『字母表』(字符串) chars。
 2 // 假如你可以用 chars 中的『字母』(字符)拼寫出 words 中的某個『單詞』(字符串),那么我們就認為你掌握了這個單詞。
 3 
 4 // 注意:每次拼寫時,chars 中的每個字母都只能用一次。
 5 // 返回詞匯表 words 中你掌握的所有單詞的 長度之和。
 6 
 7 // 輸入:words = ["cat","bt","hat","tree"], chars = "atach"
 8 // 輸出:6
 9 // 解釋:
10 // 可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
11 
12 // 輸入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
13 // 輸出:10
14 // 解釋:
15 // 可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
16 
17 #include <iostream>
18 #include <vector>
19 #include <string>
20 using namespace std;
21 class Solution
22 {
23 public:
24     int countCharacters(vector<string> &words, string chars)
25     {
26         int count = 0;
27         bool flag = false;                     // 標記
28         string c_chars(chars);                 // 構造c_chars保存chars
29         for (int i = 0; i < words.size(); i++) // 迭代單詞表
30         {
31             if (c_chars.size() < words[i].size()) //如果單詞的字母多於可選字母,則跳過這個單詞
32                 continue;
33             for (int j = 0; j < words[i].size(); j++) // 迭代可選擇的字母
34             {
35                 int index = c_chars.find(words[i][j]);
36                 if (index != c_chars.npos) // 能找到這個字母
37                 {
38                     flag = true;
39                     c_chars.erase(index, 1); // 從c_chars()刪除這個字母
40                 }
41                 else
42                 {
43                     flag = false; // 不能找到,意味着不能組成這個單詞
44                     break;        //跳出這次循環
45                 }
46             }
47             if (flag) // 如果符合則計數加1
48                 count += words[i].size();
49             c_chars.assign(chars); // 把chars的值在再次賦值給c_chars
50         }
51         return count;
52     }
53 };

 

最后感謝大家的閱讀,string中這些的函數組合起來可以說是威力無窮,所以還是要好好掌握的。

以上就是這次隨筆的全部內容了;其中有小部分內容參考了一些其他文章;好了,我們下次見,謝謝大家。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM