多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# C++ 程序:删除字符串中除字母之外的所有字符 > 原文: [https://www.programiz.com/cpp-programming/examples/remove-characters-string](https://www.programiz.com/cpp-programming/examples/remove-characters-string) #### 在此示例中,您将学习如何从字符串(字符串对象和 C 样式字符串)中删除所有字符。 要理解此示例,您应该了解以下 [C++ 编程](/cpp-programming "C++ tutorial")主题: * [C++ 数组](/cpp-programming/arrays) * [C++ 字符串](/cpp-programming/strings) * [C++ `for`循环](/cpp-programming/for-loop) * * * * * * ## 示例 1:删除除字母之外的所有字符 该程序接收用户输入的字符串(对象),并删除除字母之外的所有字符。 ```cpp #include <iostream> using namespace std; int main() { string line; string temp = ""; cout << "Enter a string: "; getline(cin, line); for (int i = 0; i < line.size(); ++i) { if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) { temp = temp + line[i]; } } line = temp; cout << "Output String: " << line; return 0; } ``` **输出** ```cpp Enter a string: p2'r"o@gram84iz./ Output String: programiz ``` * * * ## 示例 2:删除除字母之外的所有字符 下面的程序从用户那里输入一个字符串(C 风格的字符串),并删除除字母之外的所有字符。 ```cpp #include <iostream> using namespace std; int main() { char line[100], alphabetString[100]; int j = 0; cout << "Enter a string: "; cin.getline(line, 100); for(int i = 0; line[i] != '\0'; ++i) { if ((line[i] >= 'a' && line[i]<='z') || (line[i] >= 'A' && line[i]<='Z')) { alphabetString[j++] = line[i]; } } alphabetString[j] = '\0'; cout << "Output String: " << alphabetString; return 0; } ``` **输出** ```cpp Enter a string: P2'r"o@gram84iz./ Output String: Programiz ```