以下是一个使用 C++ 编写的函数来删除字符串中的空格和非字母数字字符,并输出过滤后字符串的字符个数的示例代码:\n\ncpp\n#include <iostream>\n#include <string>\n#include <cctype>\n\nint filterString(std::string& str) {\n int count = 0;\n int i = 0;\n while (i < str.length()) {\n if (isspace(str[i])) {\n str.erase(i, 1);\n } else if (!isalnum(str[i])) {\n str.erase(i, 1);\n } else {\n count++;\n i++;\n } \n }\n return count;\n}\n\nint main() {\n std::string text = "Donald Trump is bracing for his most legally perilous week since he left the White House, with the Manhattan district attorney likely to bring criminal charges against him over his role in paying hush money to adult film star Stormy Daniels, as he huddled this weekend to strategize his legal and political responses. The former US president has posted in all-caps on his Truth Social platform that he expected to be “ARRESTED ON TUESDAY OF NEXT WEEK” and called for his supporters to engage in protests – an ominous echo of his tweets urging protests in the lead-up to the January 6 US Capitol attack.";\n\n int characterCount = filterString(text);\n std::cout << "过滤后字符串的字符个数:" << characterCount << std::endl;\n\n return 0;\n}\n\n\n运行上述代码,将输出过滤后字符串的字符个数为342。

C++ 字符串过滤:删除空格和非字母数字字符 - 代码示例

原文地址: https://www.cveoy.top/t/topic/pC0M 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录