练习12.23
字符串常量
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 int main() 7 { 8 char a[] = "hello"; 9 char b[] = "world"; 10 char * pa = new char[10]; 11 pa = a; 12 for (auto i = 0; i != 5; ++i) 13 cout << pa[i]; 14 cout << endl; 15 for (auto i = 0,j = 5; i != 5; ++i, ++j) 16 { 17 pa[j] = b[i]; 18 } 19 for (auto i = 0; i != 10; ++i) 20 cout << pa[i]; 21 cout << endl; 22 system("pause"); 23 return 0; 24 }
string对象
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 int main() 7 { 8 string str1; 9 string str2; 10 while (cin >> str1 >> str2) 11 { 12 string * str = new string[50]; 13 *str = str1 + str2; 14 cout << *str << endl; 15 delete[] str; 16 } 17 system("pause"); 18 return 0; 19 }
练习12.24
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 int main() 7 { 8 string str1; 9 while (cin >> str1) 10 { 11 char * str = new char[str1.size()]; 12 for (auto i = 0; i != str1.size(); ++i) 13 str[i] = str1[i]; 14 for (auto i = 0; i != str1.size(); ++i) 15 cout << str[i]; 16 cout << endl; 17 delete[] str; 18 } 19 system("pause"); 20 return 0; 21 }
可以使用输入的字符串的长度来动态的分配字符长度;
练习12.25
1 delete[] pa;
时间: 2024-10-13 02:21:02