C++ <string>常用函数记录

1. swap(s1,s2); // 交换两个字符串,长度不相等也可以

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string  = "abc", b = "bb";
    swap(a, b);
    
    cout << a << " " << b << endl;
    
    
    
    return 0;
}

2. s.size(); 或 s.length(); // 返回字符串字符个数

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "abc";
    
    cout << s.size() << " " << s.length() << endl;
    
    return 0;
}

 

3. s.empty(); // 返回字符串是否为空,若空则true,非空则false

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "abc";
    
    if(s.empty()) cout << "empty" << endl;
    else cout << "not empty" << endl;
    
    return 0;
}

4.s.append(ss); // 添加函数,将ss添加到后方

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "abc";
    
    cout << s << endl;
    
    s.append("def");
    
    cout << s << endl;
    
    
    return 0;
}

5. s.insert(2, ss); // 插入函数,在s字符串的第二个字符后插入ss

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "abc";
    
    cout << s << endl;
    
    s.insert(2, "fff");
    
    cout << s << endl;
    
    
    return 0;
}

6. s = s.substr(n); // 删除前n个字符

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "abcdef";
    
    cout << s << endl;
    
    s = s.substr(2);
    
    cout << s << endl;
    
    
    return 0;
}

7. int pos = a.find('A', 0); // 前面位置开始查找,查找A字符最早出现的位置,若没找到,则返回string::npos

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "abcdefa";
    
    int posA = s.find("a", 0);
    cout << posA << endl;
    
    int posC = s.find("c", 0);
    cout << posC << endl;
    
    
    return 0;
}

8. s.erase(0, 2); // 删除函数,删除字符串从0位置起的后2个字符

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "abcdef";
    
    cout << s << endl;
    
    s.erase(0, 2);
    
    cout << s << endl;
        
    return 0;
}

9. s.substr(2, 5); // 复制函数,复制字符串从2位置开始,长度为5的字符

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

int main()
{
	string str = "0123456789";
	
	string s = str.substr(2, 5);
	
	cout << s << endl;
	
	return 0;
} 

  • 16
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值