Homework Introduction

字符数组和字符串

C++中,字符串被存储在char类型的数组中。

  • 字符串的末尾位置字符是 \0,空字符 null character
  • 非打印字符,其 ASCII 码值为 0。
  • 数组容量必须至少比待存储字符串中的字符多 1。
  • 字符串声明:char name[5];
  • 字符串和字符
    • 'A' 占一个字节
    • "A" 占两个字节,包括 '\0'

字符串初始化

  • char ch[12] = { 'n', 'i', 'c', 'e', ' ', 'c', 'a', 't', '.', '\0' };
  • char ch1[12] = "nice cat.";

#include <iostream>
using namespace std;
 ​
int main() {
 ​
     //  char str[110] = {'a', 'b', 'c', 'd', '\0'};
     //  cout << str << endl;
     //  
     //  char str2[110] = {'h', 'e', 'l', 'l', 'o', '\0'};
     //  cout << str2 << endl;
 ​
 ​
     // 必须有 '\0' 作为终止,否则可能会出现乱码
     char str[110];
     str[0] = 'a';
     cout << str << endl;
     
     char str2[110];
     str2[0] = 'b';
     cout << str2 << endl;
     
     char str3[110];
     str3[0] = 'c';
     cout << str3 << endl;
     
     return 0;
 }

获取带空格字符串

  • cin.getline(数组名, 数组长度)
  • cin 与 cin.getline() 连用时,cin 后面加上 cin.ignore(),清除缓冲区。
#include <iostream>
#include <cstdio>
using namespace std;

const int N = 110;

// char str[N] = {'a', 'b', 0, 'c'};
// char str[N] = "hello cat";
char str[N];

int main() {
 ​
     //  cin >> str;
     cin.getline(str, N);
     cout << str << endl;
 ​
     return 0;
 }

image

string类

  1. string 类型声明:string s;
  2. string 类型输入:cin >> s;
  3. 输入带空格的字符串:getline(cin, s);
  4. string 类型输出:cout << s;
  5. string 类型初始化:string s("abc"); string s = "abc";

string 统一转大/小写:

#include <algorithm>
transform(s.begin(), s.end(), s.begin(), ::toupper);
transform(s.begin(), s.end(), s.begin(), ::tolower);

string 翻转:

#include <algorithm>
reverse(s.begin(), s.end());
  • s.size()
  • s.empty()
  • stoi(s)
  • to_string(num)
  • s.substr(pos, len)
  • s.erase(pos, len)
  • s.find(p)
  • s.insert(pos, p)

Problem

Please claim the assignment to see the problems.
Status
Live...
Problem
5
Open Since
2024-2-10 0:00
Deadline
2036-8-23 23:59
Extension
24 hour(s)