#include "stdafx.h" #include <iostream> #include <string>//make string class available usingnamespace std; int main(int argc, char* argv[]) { char charr1[20]; char charr2[20]="jaguar"; string str1; string str2="panther"; cout<<"Enter a kind of feline: "; cin>>charr1; cout<<"Enter another kind of feline: "; cin>>str1; cout<<"Here are som felines:\n"; cout<<charr1<<""<<charr2<<""<<str1<<""<<str2<<endl; cout<<"The third letter in "<<charr2<<" is "<<charr2[2]<<endl; cout<<"The third letter in "<<str2<<" is "<<str2[2]<<endl; return0; }
第二個程序:賦值、拼接和附加
#include "stdafx.h" #include <iostream> #include <string> usingnamespace std; int main(int argc, char* argv[]) { string s1="penguin"; string s2,s3; cout<<"You can assign one string object to another: s2=s1\n"; s2=s1; cout<<"s1: "<<s1<<", s2: "<<s2<<endl; cout<<"You can assign a C-style string to a string object.\n"; cout<<"s2=\"buzzard\"\n"; s2="buzzard"; cout<<"s2: "<<s2<<endl; cout<<"You can concatenate strings: s3=s1+s2\n"; s3=s1+s2; cout<<"s3: "<<s3<<endl; cout<<"You can append strings.\n"; s1+=s2; cout<<"s1+=s2 yields s1 = "<<s1<<endl; s2+=" for a day"; cout<<"s2 += \"for a day\" yields s2 = "<<s2<<endl; return0; }
第三個程序:string對象的技術和用于字符數組的技術的對比
#include "stdafx.h" #include <iostream> #include <string>//make string class available #include <cstring>//C-style string library usingnamespace std; int main(int argc, char* argv[]) { char charr1[20]; char charr2[20]="jaguar"; string str1; string str2="panther"; //assignment for string objects and character arrays str1=str2; //copy str2 to str1 strcpy(charr1,charr2); //copy charr2 to charr1 //appending for string objects and character arrays str1 +=" paste"; //add paste to end of str1 strcat(charr1," juice"); //add juice to end of charr1 //finding the length of a string object and a C-style string int len1=str1.size(); //obtain length of str1 int len2=strlen(charr1); //obtain lenght of charr1 cout<<"The string \""<<str1<<"\" contains "<<len1<<" characters.\n"; cout<<"The string \""<<charr1<<"\" contains "<<len2<<" characters.\n"; return0; }