答案與解析
1. 輸出字符串數組所有元素
cpp
復制
下載
#include <iostream> using namespace std;int main() {string arr[] = {"apple", "banana", "cherry"};int n = sizeof(arr)/sizeof(arr[0]); // 計算數組長度for (int i = 0; i < n; i++) {cout << arr[i];if (i != n-1) cout << ", "; // 最后一個元素不加逗號}return 0; }
解析:
-
sizeof(arr)/sizeof(arr[0])
計算數組長度。 -
循環遍歷數組,用逗號分隔輸出元素。
2. 統計所有字符串總字符數
cpp
復制
下載
#include <iostream> using namespace std;int main() {string arr[] = {"cat", "dog", "fish"};int total = 0;for (int i = 0; i < 3; i++) {total += arr[i].length(); // 累加每個字符串的長度}cout << "總字符數: " << total