c++ 字符串 std::string 的初步入门

#include <iostream>
#include <ostream>
#include <string>

// 与 python 的字符串类型极其相似的 c++ 字符串: std::string

int main() {
  // using namespace std::cin;

  // 初步对比数组与c++字符串的声明方式:
  char a[15]{"hello world!"};
  std::string b{"hello python!"};
  std::cout << a << std::endl << b << std::endl;

  // c++字符串可以直接使用下标:
  char a[15]{"hello python!"};
  std::string b{"hello cpp!"};
  std::cout << b << " 的第5个字符是: " << b[4] << '\n';
  // 如果超过最大下标, 无论是数组还是字符串都不会报错, 要小心!:
  std::cout << "数组: " << a[20] << "\nc++字符串: " << b[21] << std::endl;

  // 数组不可以赋值给另外一个数组, 但是c++ string对象 可以赋值给另一个 c++ string对象
  std::string a{"hello world!"};
  auto b = a; // allow
  std::cout << a << std::endl << b << std::endl;

  char c[15]{"hello python!"};
  char d[15] = c; // not allow

  return 0;
}
#include <cstring>
#include <iostream>
#include <string>

int main(void) {
  std::string a{"hello "};
  std::string b{"world!\n"};

  // // 字符串拼接:
  std::string c;
  c = a + b;
  // std::cout << c << std::endl;

  // // std1 += std2 字符串末尾合并
  c += c;
  std::cout << c << std::endl;

  char a[50]{"百合无限好, "};
  char b[50]{"可惜生不了.\n"};
  char c[50]{"生不了更好, "};
  char d[50]{"可以无限搞.\n"};

  // strcat, strncat合并字符串
  strcat(a, b);
  std::cout << a << std::endl;

  // strcpy 复制字符串
  char x[50];
  strcpy(x, a);
  std::cout << x << std::endl;

  // strlen 获取字符长度
  int m = strlen(a);
  std::cout << m << std::endl;

  std::string w{"百合无限好, "};
  std::string x{"可惜生不了.\n"};
  std::string y{"生不了更好, "};
  std::string z{"可以无限搞.\n"};

  // c++ string 拼接:
  std::string i = w + x + y + z;
  std::cout << i << '\n';

  // c++ string 复制:
  std::string j = w;
  std::cout << j;

  // c++ string 获取字符串长度:
  int n;
  std::cout << (n = w.size());

  /* 数组的输入 */
  char wife1[50];
  std::cin.get(wife1, 50).get();
  std::cout << wife1 << std::endl;

  /* 字符串的输入 */
  std::string wife2;
  std::getline(std::cin, wife2);
  std::cout << wife2 << std::endl;

  // 原始字符串, 用大写的R:
  using std::cin;
  using std::cout;
  using std::endl;
  using std::getline;
  using std::string;
  char o[50]{R"(hello world \n)"};
  cout << o << endl;

  string str{R"+*(hello python \n)+*"};
  cout << str << endl;

  return 0;
}
#include <iostream>

int main(void) {
  auto a{R"+*(hello (world!) \n)+*"};
  
  std::cout << a << std::endl;

  return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值