C++ String类常用方法

1. 初始化

1.1 正确的初始化

#include <iostream>
#include <string>
using namespace std;
int main()
{
   
	string s1("Hello");
	cout << s1 << endl;
	string s2(8,'x');
	cout << s2 << endl;
	string month = "March";
	cout << month << endl;
	string s;
	s = 'n';
	cout << s << endl;
	return 0;
}

输出:
Hello
xxxxxxxx
March
n

1.2 错误的初始化

string error1 = 'c'; // 错
string error2('u'); // 错
string error3 = 22; // 错
string error4(8); // 错

2. 输入输出

  1. 支持流运算符,可以用cin cout进行输入输出
  2. 使用cin输入时,碰到空格、换行即结束,若要读入一整行,可使用getling函数
string s;
getline(cin, s); 

3. 赋值和连接

3.1 赋值

//用 = 赋值
string s1("cat"), s2;
s2 = s1;
//用 assign 成员函数复制
string s1("cat"), s3;
s3.assign(s1);
//用 assign 成员函数部分复制
string s1("catpig"), s3;
s3.assign(s1, 1, 3);	//从s1 中下标为1的字符开始复制3个字符给s3
//单个字符复制
s2[5] = s1[3] = 'a';
//逐个访问string对象中的字符
string s1("Hello");
for(int i=0;i<s1.length();i++)	//成员函数length()返回字符串长度
cout << s1.at(i) << endl;
//成员函数at会做范围检查,如果超出范围,会抛出
//out_of_range异常,而下标运算符[]不做范围检查。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值