主要内容 #
1. 一般的输出 #
前面,我们已经讲过了字符串的输出。
char str[] = "apple"; std::cout << str << std::endl; // 输出字符串
对于字符串的输出,还可以通过循环来处理。
2. 循环输出 #
小练习:
请定义一个字符串 “Hello Dashima!”,然后分别使用 while 和 for,输出字符串。
这个字符串的长度为 14
/* 请完成后,查看示例程序 */
示例代码:
#include < iostream > using namespace std; int main() { char dashima[] = "Hello Dashima!"; // while int i(0); cout << "Using while: " << endl; while (i < 14) cout << dashima[i++]; cout << endl << endl; // for 1 cout << "Using for 1: " << endl; for (int j = 0; j < 14; j++) cout << dashima[j]; cout << endl << endl; // for 2 cout << "Using for 2: " << endl; for (int j = 0; j < 14; ) cout << dashima[j++]; cout << endl << endl; return 0; }
上面的代码,使用了一个关键的前提条件,就是字符串的长度是 14 。而这是可以从题目中得到的。
4. 字符串的长度 #
下面,假如我们不能够直接使用“字符串的长度为 15 ”这个条件,要怎么做呢?
当然,首要问题就是,我们怎么从字符串本身,推导出来字符串的长度?请试一试。
提示:sizeof()
#include < iostream > using namespace std; int main() { char dashima[] = "Hello Dashima!"; int size = /* 请补全代码 */; cout << "size is " << size << endl; return 0; }
示例代码:
#include < iostream > using namespace std; int main() { char dashima[] = "Hello Dashima!"; int size = sizeof(dashima) / sizeof(dashima[0]) - 1; cout << "size is " << size << endl; return 0; }
说明:
下面的是字符串“Hello Dashima!”的表格形式,这里第五位的 32 是空格的十进制 ACSII 码值。
// 表示的是一个字符的大小 sizeof(dashima[0]); // 相当于 sizeof('H'); // 相当于 sizeof(char);
求得一个字符的大小后,再来求一下字符串的总体大小。
// 表示的是字符串的总体大小 sizeof(dashima);
那么,两者相除,自然就可以得到字符串的长度。所以
// 字符串中的元素数量 int size = sizeof(dashima) / sizeof(dashima[0]) - 1;
为什么还需要减一呢?因为真实情况的字符串样子,是这样的:
最后一位,存在一个(/0)。注意
这个(/0)也是一个十进制 ACSII 码值,它是ASCII表的第一个字符,表示空。
下面再给出 ASCII 表,方便大家查找。
最后,请试一下,用新学习的方法,改写 2.循环输出 中的代码。
完成后,请参考下面代码。
4.1 使用 while #
#include < iostream > using namespace std; int main() { char dashima[] = "Hello Dashima!"; int size = sizeof(dashima) / sizeof(dashima[0]) - 1; // while int i(0); cout << "Using while: " << endl; while (i < size) cout << dashima[i++]; return 0; }
4.2 使用 for #
#include < iostream > using namespace std; int main() { char dashima[] = "Hello Dashima!"; int size = sizeof(dashima) / sizeof(dashima[0]) - 1; // for 1 cout << "Using for 1: " << endl; for (int j = 0; j < size; j++) cout << dashima[j]; cout << endl << endl; // for 2 cout << "Using for 2: " << endl; for (int j = 0; j < size; ) cout << dashima[j++]; cout << endl << endl; return 0; }