C++primer 12.2.1节练习

练习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;

 

转载于:https://www.cnblogs.com/wuyinfenghappy/p/7449905.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值