I am just wondering how do I get a part of a string in C++, like I want to know what are the elements from 0 to i. Thanks.
+7
A:
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;
}
Will
2010-03-23 07:03:29
+1
A:
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.
paxdiablo
2010-03-23 07:03:37
+1
A:
if u mean string is an array of characters,
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;
if u mean the std::string use substr function.. as Will suggested
echo
2010-03-23 07:05:55
+1
A:
Assuming you're using the C++ std::string class
you can do:
std::string::size_type start = 0;
std::string::size_type end = 1; //don't use int. Use size type for portability!
std::string myStr = "hello";
std::string sub = myStr.substr(start,end);
std::cout << sub; //should print h
Alan
2010-03-23 07:06:25