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

前端 未结 5 2133
醉梦人生
醉梦人生 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:40

    Assuming you're using the C++ std::string class

    you can do:

    std::string::size_type start = 0;
    std::string::size_type length = 1; //don't use int. Use size type for portability!
    std::string myStr = "hello";
    std::string sub = myStr.substr(start,length);
    std::cout << sub; //should print h
    
    0 讨论(0)
  • 2020-12-11 03:41

    If the string is declared as an array of characters, you can use the following approach:

    char str[20];
    int i;
    strcpy(str, "Your String");
    
    // Now let's get the sub-string
    cin >> i;
    
    // Do some out-of-bounds validation here if you want..
    str[i + 1] = 0;
    cout << str;
    

    If you mean std::string, use substr function as Will suggested.

    0 讨论(0)
  • 2020-12-11 03:46

    You want to use std::string::substr. Here's an example, shamelessly copied from http://www.cplusplus.com/reference/string/string/substr/

    // string::substr
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main ()
    {
      string str="We think in generalities, but we live in details.";
                                 // quoting Alfred N. Whitehead
      string str2, str3;
      size_t pos;
    
      str2 = str.substr (12,12); // "generalities"
    
      pos = str.find("live");    // position of "live" in str
      str3 = str.substr (pos);   // get from "live" to the end
    
      cout << str2 << ' ' << str3 << endl;
    
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-11 03:47

    use:

    std::string sub_of_s(s.begin(), s.begin()+i);
    

    which create a string sub_of_s which is the first i-th the element in s.

    0 讨论(0)
  • 2020-12-11 03:56

    You use substr, documented here:

    #include <iostream>
    #include <string>
    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.

    0 讨论(0)
提交回复
热议问题