016-C++中新型字符串string操作

/**
 * C++ 标准库中提供了string类型专门表示字符串
 * #include<string>
 * using namespace std;
 * 
 * 使用string可以更为方便和安全的管理字符串
 * 
*/
#include <string>
#include <iostream>
using namespace std;

int main(int argc, char const *argv[])
{
  /* code */
  string s1; //空字符串
  string s2 = "helloworld"; // 定义并初始化
  string s3("helloworld");
  string s4 = string("helloworld");
  cout<<s4<<endl;
  // 获取字符串的长度
  cout<<s4.length()<<endl;
  cout<<s4.size()<<endl; // 本质上和上面一样
  cout<<s4.capacity()<<endl;

  // 字符串的比较  == != >= > <= < 
  string s5 = "world";
  cout<<"s1==s2 "<<(s1==s5)<<endl;
  cout<<"s1!=s2 "<<(s1!=s2)<<endl;
  
  // 转还为C风格的字符串
  const char* cc_str1 = s1.c_str();
  char* name = "000";
  char names[] = "jack";
  cc_str1 = name;
  cout<<"cc_str1 "<<cc_str1<<endl;
  cc_str1 = "dad";
  //cc_str1[0] = 'l';
  names[0] = 'l';
  cout<<"names "<<names<<endl;
  // 随机访问(获取字符串中某个字符)[]
  string s6 = "hello";
  cout<<s6[0]<<endl;
  s6[0] = 'd';
  cout<<s6<<endl;
  // 字符串拷贝: = 
  string s7 = "hello";
  string s8 = s7;
  cout<<s8<<endl;

  // 字符串连接 + +=
  string s9  = "hello";
  string s10 = "lucky";
  cout<<s9+s10<<endl;
  return 0;
}

输出如下:

1 warning generated.
helloworld
10
10
22
s1==s2 0
s1!=s2 1
cc_str1 000
names lack
h
dello
hello
hellolucky

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值