【分享】字符串常见函数学习笔记

Memories on the corner / 2023-08-22 / 原文

字符串常见函数学习笔记

 

1: 查找函数: find() //返回值string::npos

string s = "good good study, day day up";
int pos1 = s.find("good");//查找子串"good"
int pos2 = s.find("good", 4); //从下标4开始,查找子串"good"
cout << pos1 << endl << pos2;//输出下标

 

输出内容:

0
5

2: 获取子串函数:substr()

string s = "good good study, day day up";
string s1 = s.substr(0,4);//截取下标0-4的所有子串 
string s2 = s.substr(9,5);//截取从下标9开始,长度为5的子串
string s3 = s.substr(5);//截取下标5以上的所有子串 
cout << s1 << endl << s2 << endl << s3;//输出子串

 

输出内容:

诶好像有点问题……

good
 stud
good study, day day up

 


3: 删除函数:erase()

注:会改变原字符串!

string s = "abcdef";
string ss = "abcdef";
string s1 = s.erase(1,2);//把下标1-2中间的子串删除 
string s2 = s.erase(1);//把下标1后面的所有子串删除 
cout << s1 << endl << s2;//输出操作后的字符串 

 

输出内容:

adef
a

 


4:替换函数:replace()

注:会改变原字符串!

string s1 = "topscode";
string s2 = "coding";
string s3 = s1.replace(4,4,s2);//把s1从下标4到后4个替换成s2 
cout << s3;//输出替换后的字符串 

 

输出内容:

topscoding

 


5:插入函数:insert()

注:会改变原字符串!

string s1 = "topscodecoding";
string s2 = "good";
string s3 = s1.insert(3,s2);//从s1下标3左边开始,插入s2 
cout << s3;//输出插入后的字符串 

 

输出内容:

topgoodscodecoding

 


6:翻转函数:reverse()

注:字符串的第一个字符为begin(),最后一个字符为end()

注:会改变原字符串!

string s1 = "good good study";
string s2 = "day day up";
reverse(s1.begin(), s1.end()); //把s1整体翻转过来
reverse(s2.begin() + 4, s2.end() - 3); //把s2从下标4开始到下标倒数3全部翻转
cout << s1 << endl << s2;//输出翻转后的字符串

 

输出内容:

yduts doog doog
day yad up

 

7:判空函数:empty()

string s1 = "Hello";
if (s1.empty()) {//判断字符串s1是否为空串
    cout << 1;
} else {
    cout << 0;
}

 

输出内容:

1

8:清空函数:clear()

注:会改变原字符串!

string a = "topscoding";
a.clear();//将a的内容清空,变为空串

 

输出内容:

9:追加函数:append()

注:会改变原字符串!

string a = "topscoding";
a.append("hello");//将a的内容增添一截
cout << a;

 

输出内容:

topscodinghello

 


字符串字典序

(1)比如两个字符串'abcd”和“abdd”比较大小。从第一个字符开始逐位比较,第一个字符不相等,谁的ASCII码值小谁的字典序就小。若第一个相等,继续逐位比较后续字符。比较到字母c<字母d,所以第一个字符串”abcd“字典序较小。

(2)再比如“hist“和“historv“比较大小。若逐位比较都相等,但其中一个没有后续的字符了,则较短的串“hist”字典序较小。

  • 使用sort()可以对字符串进行字典序排序,字符按ASCII码值由小到大排列

sort() 单个字符串排序

string s = "yuxingran1633";
sort(s.begin(), s.end()); //按字典序将字符串排序
cout << s;

 


sort() 多个字符串排序

string s[3] = {"agddbad", "daf", "adfw"};
sort(s, s + 3); //按字典序将字符串排序
for (int i = 0; i < 3; i++) {
    cout << s[i] << endl;
}

 

额外分享:

为了满足题目要求,可以再对字符串排序的时候用上cmp函数:

bool cmp( ... ) {
    if( ... ) {
        return ... ;
    } else {
        ... ;
    }
    ... ...
}
int main() {
    ...
    
    sort(... , ... ,cmp);
    ...
    return 0;
}

 


例题:

ASCII码排序

字符串查找

单词替换

国名排序

字符串练习二

集合运算(set)

本文内容就这么多,希望对你有帮助!