string——学习记录

#include "string"
#include "iostream"

using namespace std;

int main(){
    string ss;
    ss "aaa";
    string sa,sb;
    cin >> sa;
    sb = sa;

    ss += 'a';
    ss += "aaa";
    ss.insert(ss.begin() + 1,'b');//在ss[1]之前!插入b


    //替换
    ss="abcdefg";
    ss.replace(2,2,"999");//结果ss为ab999efg;
    ss.replace(2,0,"aaa");//从第二个字符开始将连续0个元素替换为aaa(就是将aaa插入到了第二个字符前面了)

    //删除部分
    ss = " ";//清空字符串
    string::iterator it = ss.begin();
    ss.erase(it+1);
    ss.erase(it+1,it+3);

    //查找
    string st1("babbabab");
    cout << st1.find('a') << endl;//1   由原型知,若省略第2个参数,则默认从位置0(即第1个字符)起开始查找
    cout << st1.find('a', 0) << endl;//1
    cout << st1.find('a', 1) << endl;//1   
    cout << st1.find('a', 2) << endl;//4   在st1中,从位置2(b,包括位置2)开始,查找字符a,返回首次匹配的位置,若匹配失败,返回npos
    cout << st1.find('c', 0) << endl;//4294967295
    cout << st1.find('a', 100) << endl;//4294967295   当查找的起始位置超出字符串长度时,按查找失败处理,返回npos


}

转化及stringstream用法

#include <iostream>
#include <string>
#include <set>
#include <sstream> 
#include <vector>
using namespace std;
vector<string> a;

int main(int argc, char** argv) {

//  string buf;
//  cout << s << endl;//不会因为空格不输出 
//  stringstream ss ;//用于去空格
//  ss.str("");//清空,如果是<<则是后面添加 
//  ss << s;
//  cout << ss << endl; //  是一个0x70fd28 
//  a.push_back(ss);    //根本就是不是string类型,报错 
//  while(ss >> buf){   //起到分割作用 
//      a.push_back(buf);
//  } 
//  ss >> buf;
//  a.push_back(buf); 
//  for(vector<string>::iterator it = a.begin(); it != a.end(); it++){
//      cout << *it <<endl;
//  }
    //int转string 
    int aa = 30;
//  stringstream ss;
//  ss<<aa; 
//  string s1 = ss.str();
//  cout<<s1<<endl; // 30

//  string s2;
//  ss>>s2;
//  cout<<s2<<endl; // 30

    //string转int,但只能收一个,所以要转的话要多次转 
//  string s = "7 # """;
//  stringstream ss;
//  ss<<s;
//  int i;
//  ss>>i;
//  cout<<i<<endl; 

    string s = "75 4";
    stringstream ss;
    ss<<s;
    int i;
    while(ss >> i) {
    cout<<i<<endl; 
    }

    //注意不是转化ASCII,就是整数转成整数,如果string里面有别的,比如# 就不转
}

参考:
stringstream中转化中的clear误区

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值