设为首页 加入收藏

TOP

3.3.1 String Tester程序简介
2013-10-07 14:43:13 来源: 作者: 【 】 浏览:59
Tags:3.3.1 String Tester 程序 简介

3.3  使用string对象

无论是编写完整的字谜游戏还是简单地存储玩家名字,第1章简单介绍过的string对象都非常适合于处理这样的字符序列。string实际上是对象,它提供的成员函数允许用string对象完成一系列任务,从简单地获取对象长度到复杂的字符替换等等。另外,string的定义方式使它可以直观地与已知的一些运算符一起使用。

3.3.1  String Tester程序简介

String Tester程序使用了一个等于"Game Over!!!"的字符串,并报告它的长度、每个字符的索引(位置序号)以及是否存在特定的子字符串。另外,程序还将该string对象的部分内容擦除。该程序的运行结果如图3-3所示。

 
图3-3  通过常见的运算符和string成员函数可以
对string对象进行组合、修改和擦除操作
从Course Technology网站(www.courseptr.com/downloads)或本书合作网站(http://www. tupwk.com.cn/downpage)上可以下载到该程序的代码。程序位于Chapter 3文件夹中,文件名为string_tester.cpp。
  1. // String Tester  
  2. // Demonstrates string objects  
  3. #include <iostream> 
  4. #include <string> 
  5. using namespace std;  
  6. int main()  
  7. {  
  8. string word1 = "Game";  
  9. string word2("Over");  
  10. string word3(3, '!');  
  11. string phrase = word1 + " " + word2 + word3;  
  12. cout << "The phrase is: " << phrase << "\n\n";  
  13. cout << "The phrase has " << phrase.size() << " characters in it.\n\n";  
  14. cout << "The character at position 0 is: " << phrase[0] << "\n\n";  
  15. cout << "Changing the character at position 0.\n";  
  16. phrase[0] = 'L';  
  17. cout << "The phrase is now: " << phrase << "\n\n";  
  18. for (unsigned int i = 0; i < phrase.size(); ++i)  
  19. {  
  20. cout << "Character at position " << i << " is: " << phrase[i] << endl;  
  21. }  
  22. cout << "\nThe sequence 'Over' begins at location ";  
  23. cout << phrase.find("Over") << endl;  
  24. if (phrase.find("eggplant") == string::npos)  
  25. {  
  26. cout << "'eggplant' is not in the phrase.\n\n";  
  27. }  
  28. phrase.erase(4, 5);  
  29. cout << "The phrase is now: " << phrase << endl;  
  30. phrase.erase(4);  
  31. cout << "The phrase is now: " << phrase << endl;  
  32. phrase.erase();  
  33. cout << "The phrase is now: " << phrase << endl;  
  34. if (phrase.empty())  
  35. {  
  36. cout << "\nThe phrase is no more.\n";  
  37. }  
  38. return 0;  
  39. }  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇3.1.3 在for循环中使用空语句 下一篇3.1.4 for循环的嵌套

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: