2010-03-23 16 views

risposta

15

Si desidera utilizzare std::string::substr. Ecco un esempio, spudoratamente copiato da 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; 
} 
2

Si utilizza substr, documentato 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; 
} 

È inoltre possibile quindi trattarla come una stringa in stile C (non modificabile) utilizzando c_str, documentato here.

1

se u significa stringa è un array di caratteri,

char str[20]; 
int i; 
strcpy(str,"Your String"); 

//Now lets get the substr 
cin>>i; 

// do some out-of-bounds validation here if u want.. 
str[i+1]=0; 
cout<<str; 

se u significa la funzione substr std::string uso .. come volontà suggerito

1

Supponendo che si sta utilizzando il C++ std::string classe

si può fare:

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

uso:

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

che creano una stringa sub_of_s che è il primo i-th dell'elemento in s.

Problemi correlati