Skip to content

Latest commit

 

History

History
67 lines (59 loc) · 1.83 KB

211004.md

File metadata and controls

67 lines (59 loc) · 1.83 KB

c++ 字符与字符串

字符:char

  1. 不能用双引号
  2. 不能是多字符,只能单个字符
  3. 占位空间 1
#include<iostream>
using namespace std;

int main () {
    char a = 'a';
    cout << "char 类型" << a << " 占用空间 " << sizeof(a) << endl;
    return 0;
}

字符串:char str[]

  1. 沿用 c 语言
  2. 使用双引号
  3. 占位空间随着字符串长度变化
#include<iostream>
using namespace std;

int main () {
    char b1[] = "abc测试字符串12";
    char b2[] = "abc测试字符串12abc测试字符串12";
    // 占用空间 21
    cout << "char[] 类型" << b1 << " 占用空间 " << sizeof(b1) << endl;
    // 占用空间 41
    cout << "char[] 类型" << b2 << " 占用空间 " << sizeof(b2) << endl;
    return 0;
}

字符串:string

  1. 使用双引号
  2. 占位空间:32
  3. 需要引用 string 库
#include<iostream>
#include<string>
using namespace std;

int main () {
    string c1 = "a";
    string c2 = "abc测试字符串12";
    string c3 = "abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12abc测试字符串12";
    // 占用空间 32
    cout << "string 类型" << c1 << " 占用空间 " << sizeof(c1) << endl;
    // 占用空间 32
    cout << "string 类型" << c2 << " 占用空间 " << sizeof(c2) << endl;
    // 占用空间 32
    cout << "string 类型" << c3 << " 占用空间 " << sizeof(c3) << endl;
    return 0;
}