作業練習¶
Problem. 輸出第一個字元¶
輸入一個字串,輸出第一個字元。
範例輸入:
範例輸出:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
cin >> text;
cout << text[0] << endl;
return 0;
}
Problem. 統計字母 a¶
輸入一個字串,計算裡面有幾個小寫 a。
範例輸入:
範例輸出:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
int count = 0;
cin >> text;
for (int i = 0; i < text.length(); i++)
{
if (text[i] == 'a')
{
count++;
}
}
cout << count << endl;
return 0;
}
Problem. 統計數字字元¶
輸入一個字串,計算裡面有幾個數字字元。
範例輸入:
範例輸出:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
int count = 0;
cin >> text;
for (int i = 0; i < text.length(); i++)
{
if (text[i] >= '0' && text[i] <= '9')
{
count++;
}
}
cout << count << endl;
return 0;
}
Problem. 尋找關鍵字¶
輸入一整行文字,如果裡面包含 C++,輸出 Found,否則輸出 Not Found。
範例輸入:
範例輸出:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
getline(cin, text);
if (text.find("C++") != string::npos)
{
cout << "Found" << endl;
}
else
{
cout << "Not Found" << endl;
}
return 0;
}
Problem. 取出信箱帳號¶
輸入一個 Email,輸出 @ 前面的帳號。
範例輸入:
範例輸出:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string email;
cin >> email;
int position = email.find("@");
cout << email.substr(0, position) << endl;
return 0;
}
Problem. 找出最長名字¶
輸入 5 個名字,輸出最長的名字。
範例輸入:
範例輸出:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string names[5];
for (int i = 0; i < 5; i++)
{
cin >> names[i];
}
string longestName = names[0];
for (int i = 1; i < 5; i++)
{
if (names[i].length() > longestName.length())
{
longestName = names[i];
}
}
cout << longestName << endl;
return 0;
}
Problem. 留言黑名單¶
輸入一整行留言,如果包含 bad 或 hate,輸出 Blocked,否則輸出 OK。
範例輸入:
範例輸出: