
练习3.6
#include <iostream>
using namespace std;
#include <string>
int main() {
char a = 'X';
string s;
getline(cin,s);
for (auto& c : s) //对于s中的每个字符(注意:c是引用)
c = a;
cout << s;
return 0;
}
字符串里面的所有字符是包含空格的。因此空格的地方也为X

练习3.7
将auto更改为char,结果一样,说明string里面的每个字符领出来,类型为char类型。
#include <iostream>
using namespace std;
#include <string>
int main() {
char a = 'X';
string s;
getline(cin,s);
for (char & c : s) //对于s中的每个字符(注意:c是引用)
c = a;
cout << s;
return 0;
}

练习3.8
for循环语句
#include <iostream>
using namespace std;
#include <string>
int main() {
string s;
getline(cin, s);
for (decltype(s.size())index = 0;
index != s.size(); ++index)
s[index] = 'X';
cout << s;
return 0;
}

while循环语句
#include <iostream>
using namespace std;
#include <string>
int main() {
string s;
getline(cin, s);
decltype(s.size())index = 0;
while (index != s.size()) {
s[index] = 'X';
index = index + 1;
}
cout << s;
return 0;
}

范围for语句更加简洁,自动循环所有字符,不用考虑终止条件。
练习3.9
程序可以运行,s是一个空字符串,s[0]的结果是未定义的,不要这样做。这种错误不会被编译器发现,而是在运行时产生一个不可预知的值。
练习3.10
#include <iostream>
using namespace std;
#include <string>
int main() {
string s;
getline(cin, s);
for (auto& c : s) //对于s中的每个字符
if (ispunct(c)) //如果该字符是标点符号
c = ' ';
cout << s;
return 0;
}


上面的代码是将标点符号变成了空格,并没有删除,下面的代码可以实现删除标点符号。
#include <iostream>
using namespace std;
#include <string>
int main() {
string s;
getline(cin, s);
string result;
for (auto& c : s)
if (!ispunct(c))
result += c;
cout << result;
return 0;
}

练习3.11
合法,系统没报错,c的类型除了用auto之外,只能是const char,因为s是constant string。不然系统报错
#include <iostream>
using namespace std;
#include <string>
int main() {
const string s = "Keep out!";
for (const char & c : s) {
/*...*/
}
return 0;
}
C++编程:字符串操作与循环控制
本文通过一系列C++编程练习,探讨了如何使用for循环和while循环遍历并修改字符串中的字符,包括替换字符、删除标点符号等操作。同时也展示了范围for语句在简化代码方面的优势。此外,还讨论了对常量字符串的处理方法。

被折叠的 条评论
为什么被折叠?



