How do I get a part of the a string in C++?

前端 未结 5 2150
醉梦人生
醉梦人生 2020-12-11 03:40

How do I get a part of a string in C++? I want to know what are the elements from 0 to i.

5条回答
  •  没有蜡笔的小新
    2020-12-11 03:56

    You use substr, documented here:

    #include 
    #include 
    using namespace std;
    int main(void) {
        string a;
        cout << "Enter string (5 characters or more): ";
        cin >> a;
        if (a.size() < 5)
            cout << "Too short" << endl;
        else
            cout << "First 5 chars are [" << a.substr(0,5) << "]" << endl;
        return 0;
    }
    

    You can also then treat it as a C-style string (non-modifiable) by using c_str, documented here.

提交回复
热议问题