C++中处理string对象的字符 收藏
处理string对象的字符常用方法如下: isalnum():判断字符是否是字母或数字; isalpha():判断字符是否是字母; iscntrl():判断字符是否是控制字符; isdigit():判断字符是否是数字; isgraph():判断字符是否是可打印的非空格字符; ispunct():判断字符是否是标点符号; isspace():判断字符是否是空白字符; isupper():判断字符是否是大写字母; isxdigit():判断字符是否是十六进制数; toupper():转换为大写字母; tolower():转换为小写字母。 实例:
StringDealChar.cpp:
01.#include <iostream> 02.#include <string> 03. 04.using std::cout; 05.using std::endl; 06.using std::string; 07. 08.int main() { 09. 10. string s("Hello, World!123\n"); 11. 12. //字母或数字的个数 13. string::size_type alnumCount = 0; 14. //字母的个数 15. string::size_type alphaCount = 0; 16. //控制字符的个数 17. string::size_type cntrlCount = 0; 18. //数字的个数 19. string::size_type digitCount = 0; 20. //可打印的非空格字符的个数 21. string::size_type graphCount = 0; 22. //标点符号的个数 23. string::size_type punctCount = 0; 24. //空白字符的个数 25. string::size_type spaceCount = 0; 26. //大写字母的个数 27. string::size_type upperCount = 0; 28. //十六进制数的个数 29. string::size_type xdigitCount = 0; 30. 31. for (string::size_type i = 0; i < s.size(); i++) { 32. //判断字符是否是字母或数字 33. if (isalnum(s[i])) { 34. alnumCount++; 35. } 36. //判断字符是否是字母 37. if (isalpha(s[i])) { 38. alphaCount++; 39. } 40. //判断字符是否是控制字符 41. if (iscntrl(s[i])) { 42. cntrlCount++; 43. } 44. //判断字符是否是数字 45. if (isdigit(s[i])) { 46. digitCount++; 47. } 48. //判断字符是否是可打印的非空格字符 49. if (isgraph(s[i])) { 50. graphCount++; 51. } 52. //判断字符是否是标点符号 53. if (ispunct(s[i])) { 54. punctCount++; 55. } 56. //判断字符是否是空白字符 57. if (isspace(s[i])) { 58. spaceCount++; 59. } 60. //判断字符是否是大写字母 61. if (isupper(s[i])) { 62. upperCount++; 63. } 64. //判断字符是否是十六进制数 65. if (isxdigit(s[i])) { 66. xdigitCount++; 67. } 68. } 69. 70. cout << s << endl; 71. cout << "alnumCount: " << alnumCount << endl; 72. cout << "alphaCount: " << alphaCount << endl; 73. cout << "cntrlCount: " << cntrlCount << endl; 74. cout << "digitCount: " << digitCount << endl; 75. cout << "graphCount: " << graphCount << endl; 76. cout << "punctCount: " << punctCount << endl; 77. cout << "spaceCount: " << spaceCount << endl; 78. cout << "upperCount: " << upperCount << endl; 79. cout << "xdigitCount: " << xdigitCount << endl; 80. 81. //全部转换为大写字母 82. for (string::size_type i = 0; i < s.size(); i++) { 83. s[i] = toupper(s[i]); 84. } 85. cout << s << endl; 86. 87. 88. //全部转换为小写字母 89. for (string::size_type i = 0; i < s.size(); i++) { 90. s[i] = tolower(s[i]); 91. } 92. cout << s << endl; 93. 94. 95. system("pause"); 96. return 0; 97.} 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/bingcaihuang/archive/2010/05/26/5624369.aspx |
|