c++ 字符串常用api

1.截取substr(index,size),从下标index处截取长为size的内容,深拷贝。

int main() {

    string s = "hello world";
    string s2 = s.substr(6, 5);//截取world
    cout << s << endl;//输出hello world
    cout << s2 << endl;//输出world
}

2.末尾添加字符push_back

int main() {

    string s = "hello world";
    string s2 = s.substr(6, 5);//截取world
    s2.push_back('h');//尾部添加字符h,s2=worldh
    cout << s2;//输出worlds
}

3.字符串拼接,直接使用+运算

int main() {

    string s = "hello world";
    cout << s+" HL" <<endl;//输出hello world HL
}

4.字符串长度size(),不包含最后的‘\0’字符。

int main() {

    string s = "hello world";
    cout << s.size() << endl;//输出11
}

5.字符串分割,使用stringstream API,需要添加sstream类

int main() {

    string s = "hello world HL";//原始字符串
    stringstream ss(s);//创建字符串流

    while (getline(ss, s, ' '))//依次获得按空格分开的每个字符串,并存储在s中
    {
        cout << s << endl;//依次输出hello、world、HL三个字符串
    }
}

6.查找子字符串find(),返回第一次出现的位置,没有会返回一个无穷大值。

int main() {

    string s = "hello world";
    string s2 = s.substr(6, 5);//截取s中下标为6长度为5的字符串world
    cout << s.find(s2) << endl;//输出6,world在s中第一次出现位置下标是6
    if (s.find(s + "z")>s.size())//找不到会返回一个无穷大值
    {
        cout << "no find";
    }
}

7.数字转字符串to_string,字符串转数字stoi(string to int)。记得添加sstream类。python中可以直接使用加法运算。

int main() {
    string s = "hello world";
    cout << s + to_string(512)<<endl;//输出hello world512
    cout << 10+stoi("510") << endl;//输出520
}

其他(相对使用没那么多)

8.判断是否是数字或字符isalnum(is alphabet  or num)

#include<iostream>

using namespace std;

int main()
{
	//字母数字则返回非零值,其他返回0
	cout << isalnum('4') << endl;
	cout << isalnum('a') << endl;
	cout << isalnum(',') << endl;
}

9.大小写字符转换tolower/toupper,只处理大小写字符,其他不处理,返回的是ascii码值,可以自行强制转换。

#include<iostream>

using namespace std;

int main()
{
	cout << tolower('A') << endl;//输出‘a’的ascii码值97
	cout << tolower('1') << endl;//输出‘1’的ascii码值49
	cout << (char)toupper('a') << endl;//强转为字符输出‘A’
	cout << toupper('.') << endl;//输出‘.’的ascii码值46
}

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值