C++string类

用string类包含头文件**< string >

1, 初始化:

~~string s1(“he”);
~~ string m = “march”;
~~ string s2(2,‘x’ ); //2个x

可以把字符串赋值给string对象
~~ string s;
~~ s = ‘n’ ;

string对象长度用length()读取
string支持流读取运算符

~~ string str;
~~ cin>> str;

string 支持getline函数

~~ string s;
~~ getline(cin,s);

2, 赋值和连接

1:用=赋值
2: 用assign函数复制
3:用assign成员函数部分复制
~~ string s1(“catpig”), s2;
~~ s3.assign(s1, 1, 3); //从s1下标为1的字符开始复制3个字符

4:逐个访问string对象字符:
~~string s(“he”);
~~for(int i=0; i< s.length(); i++)
cout<< s.at(i) <<endl; //at会做范围检查

5:用+连接
6:函数append连接
~~ s2.append(s1,3,s1.size()); //下标3开始,s1.size()个字符,如果没有足够字符,则复制到最后一个字符
7: 函数substr
~~string s1(hello world"), s2;
~~ s2 = s1.substr(4,5); //下标4开始5个字符

3, 寻找string中的字符

1:函数find()
2: rfind 从后向前查找
3: 函数 find_first_of()
~~ s.find_first_of()(“abcd”); //从前向后找“abcd"中任何一个字符第一次出现的地方,找到返回字母位置。
4: 函数 find_last_of()

4, 插入string中的字符

1: insert()
~~ s.insert(5, s2);
~~ s1.insert(2, s2,5,3); //==把s2下标5开始3个字符插入s1下标2的位置
2: 函数 replace替换字符
~~ s.replace(2,3, “haha”,1,2);
3: ==c_str()==转换c语言式char*字符串
4: data()

5, 字符串流处理

#include< string>
#include< iostream>
#include< sstream>

字符串留处理:

  • 字符串输入流istringstream
  • 字符串输出流ostringstream
#include<bits/stdc++.h>
using namespace std;
main()
{
 string input("Input test 123 4.7 A");
 istringstream inputString(input);
 string s1, s2;
 int i;
 double d;
 char c;
 inputString >> s1 >>s2>>i>>d >>c;
 cout << s1<< endl<< s2<<endl;
 cout << i<<endl << d<<endl<< c<< endl;
 long L;
 if(inputString >> L)
  cout << "long\n";
 else
  cout <<"empty\n";
 ostringstream outputString;
 int a = 10;
 outputString << "This "<<a<<" ok"<<endl;
 cout<< outputString.str();
}

运行结果:

Input
test
123
4.7
A
empty
This 10 ok
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值