C++——std::String

string::string

// string constructor
#include <iostream>
#include <string>

int main ()
{
  std::string s0 ("Initial string");  //根据已有字符串构造新的string实例

  // constructors used in the same order as described above:
  std::string s1;             //构造一个默认为空的string
  std::string s2 (s0);         //通过复制一个string构造一个新的string
  std::string s3 (s0, 8, 3);    //通过复制一个string的一部分来构造一个新的string。8为起始位置,3为偏移量。
  std::string s4 ("A character sequence");  //与s0构造方式相同。
  std::string s5 ("Another character sequence", 12);  //已知字符串,通过截取指定长度来创建一个string
  std::string s6a (10, 'x');  //指定string长度,与一个元素,则默认重复该元素创建string
  std::string s6b (10, 42);      // 42 is the ASCII code for '*'  //通过ASCII码来代替s6a中的指定元素。
  std::string s7 (s0.begin(), s0.begin()+7);  //通过迭代器来指定复制s0的一部分,来创建s7

  std::cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
  std::cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6a: " << s6a;
  std::cout << "\ns6b: " << s6b << "\ns7: " << s7 << '\n';
  return 0;
}

//Output:
//s1: 
//s2: Initial string
//s3: str
//s4: A character sequence
//s5: Another char
//s6a: xxxxxxxxxx
//s6b: **********
//s7: Initial

一些实例:
stringstream通常是用来做数据转换的。
相比c库的转换,它更加安全,自动和直接。
例子一:基本数据类型转换例子 int转string

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

int main()
{
    std::stringstream stream;
    std::string result;
    int i = 1000;
    stream << i; //将int输入流
    stream >> result; //从stream中抽取前面插入的int值
    std::cout << result << std::endl; // print the string "1000"
} 

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

他人是一面镜子,保持谦虚的态度

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值