Dive Deeper

Credit: Peipei @ Sprout 2021

Dive Deeper

``std::cout << "Hello World!" << std::endl;``
``"Hello World!"``
``'H','e','l','l','o',' ','W','o','r','l','d','!'``

字元

``char c = 'H';``

``````char c1 = 'A'; // ok
char c2 = "A"; // error``````

字元

``std::cout << (int)'H' << std::endl;``
``72``

字元

``'H' == 72``

?

``````char a = 'H';
char b = 72;

if (a == b)
std::cout << "Same" << std::endl;
else
std::cout << "Oops..." << std::endl;``````

字元

``'H' == 72``

'A': 65,  'B': 66,  'C': 67 , ... , 'Z': 90

'a': 97,  'b': 98,  'c': 99 , ... ,  'z': 122

'0': 48,  '1': 49,  '2': 50 , ... , '9': 57

字元

ASCII 表背不起來...

``````char b = 'a' + 1;
// b is 'b'

char Z = 'A' + 25;
// Z is 'Z'

char one = '2' - 1;
// one is '1';``````

tab '\t'

' '\''
\ '\\'
" '\"'

'\r'

字元

``a``
``A``

字串

``char s[6] = "Hello";``

``````char s1[2] = "A"; // ok
char s2[2] = 'A'; // error``````

字串

``char s[6] = "Hello";``

"Hello"長度只有5，為什麼陣列長度宣告6？

字串

``char s[6] = "Hello";``
``char s[6] = {'H','e','l','l','o','\0'};``

'\0'代表一個字串的結束

字串

``````char s1[6] = "Hello"; // ok
char s2[6] = {'H', 'e', 'l', 'l', 'o', 0}; // ok``````
``````char s[6] = "Hello"; // ok
s = "World"; // error
s = {'W', 'o', 'r', 'l', 'd', '\0'}; // error``````

字串

``````char s[6] = "Hello";
std::cout << s << std::endl;``````

cout 將字串(字元陣列)裡的字元一一印出，

字串

``````char a[5] = {'H', 'e', 'l', 'l', 'o'};
char b[6] = "World";
std::cout << a << std::endl;
std::cout << b << std::endl;``````

``````HelloWorld
World``````

字串

``Hello World``

``````char s[100];
std::cin >> s;
std::cout << s << std::endl;``````

``Hello``

字串常用函式

#include <cstring>

字串常用函式

strlen(s)

``````char s[100] = "Sprout";
std::cout << strlen(s) << std::endl;``````

``6``

字串常用函式

strlen(s)

``````char s[100] = "Sprout";
for (int i = 0; i < strlen(s); i++)
std::cout << s[i] << std::endl;``````

``````char s[100] = "Sprout";
int len = strlen(s);
for (int i = 0; i < len; i++)
std::cout << s[i] << std::endl;``````

字串常用函式

strcmp(a, b)

``````char a[100] = "same";
char b[100] = "same";
if (strcmp(a, b) == 0) {
std::cout << "same strings" << std::endl;
} else {
std::cout << "different" << std::endl;
}``````

字串常用函式

strcmp(a, b)

``````char a[100] = "same";
char b[100] = "same";
if (a == b) {
std::cout << "same strings" << std::endl;
} else {
std::cout << "different" << std::endl;
}``````

字串常用函式

strcpy(dest, src)

``````char a[100] = "old";
a = "new";``````

``````char a[100] = "old";
strcpy(a, "new");
// now a is "new"``````

字串常用函式

strcat(dest, src)

``````char a[100] = "front";
a += "back"; // error``````

``````char a[100] = "front";
strcat(a, "back");
// a is now "frontback"``````

By JT

• 944