//学习使用string类 2013-10-18 lingc #include <iostream> #include <string>//include this head file <string> using namespace std; int main() { string myString1; myString1 = "hello world,i am lingc!";// can no use the ' ' string myString2(myString1,5,12);// begin at index 5, and count 12 elements string myString3(4,'z'); cout<<"how to use the class of string,by lingc at 2013-10-18"<<endl; cout<<"myString1 is "<< myString1 <<endl; cout<<"myString2 is "<< myString2 <<endl; cout<<"myString3 is ""<< myString3 <<"" and its length is " << myString3.length() <<endl; //combine the string string comString = myString1 + " " + "i am so sleepy."; cout << comString <<endl; //the follow is wrong 不能用+来连接字符串字面量 //string comString2 = " " + "so sleepy " + myString1; //corect is to the right string comString2 = " " + ("so sleepy " + myString1); cout<< comString2 << endl; return 0; }
可以使用string[] 来访问字符串中的字符:
#include <iostream> #include <string> using namespace std; int main() { string mystring = "hello world."; cout<< mystring <<endl; for (size_t i=0; i<mystring.length(); i++) { mystring[i] = toupper(mystring[i]); } cout<< mystring <<endl; return 0; }