跳轉到

作業練習

Problem. 輸出第一個字元

輸入一個字串,輸出第一個字元。

範例輸入:

banana

範例輸出:

b
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string text;

    cin >> text;

    cout << text[0] << endl;

    return 0;
}

Problem. 統計字母 a

輸入一個字串,計算裡面有幾個小寫 a

範例輸入:

banana

範例輸出:

3
#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. 統計數字字元

輸入一個字串,計算裡面有幾個數字字元。

範例輸入:

abc123x9

範例輸出:

4
#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

範例輸入:

I love C++ very much

範例輸出:

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,輸出 @ 前面的帳號。

範例輸入:

peter@gmail.com

範例輸出:

peter
#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 個名字,輸出最長的名字。

範例輸入:

John
Mary
Wilson
Candy
Allen

範例輸出:

Wilson
#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. 留言黑名單

輸入一整行留言,如果包含 badhate,輸出 Blocked,否則輸出 OK

範例輸入:

I hate this game

範例輸出:

Blocked
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string message;

    getline(cin, message);

    if (message.find("bad") != string::npos ||
        message.find("hate") != string::npos)
    {
        cout << "Blocked" << endl;
    }
    else
    {
        cout << "OK" << endl;
    }

    return 0;
}