第 5 章 string

📅 2026/7/13 22:58:16 👁️ 阅读次数 📝 编程学习
第 5 章 string
1.标题统计
#include<bits/stdc++.h> using namespace std; int main() { string s; getline(cin, s); cout << s.size() << endl; return 0; }
2.⽯头剪⼦布
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; for(int i=0; i<n; i++) { string a,b; cin>>a>>b;//读入两个字符串 if(a[0]==b[0])cout<<"Tie\n";//首位相同,平局 else if(a[0]=='R') { if(b[0]=='P')cout<<"Player2\n"; else cout<<"Player1\n"; } else if(a[0]=='P') { if(b[0]=='S')cout<<"Player2\n"; else cout<<"Player1\n"; } else if(a[0]=='S') { if(b[0]=='R')cout<<"Player2\n"; else cout<<"Player1\n"; }//以上是逐个判断,按照 Player1 的情况分类讨论 //因为讨论过平局了,可以只分两种情况考虑 //记得使用 else-if } return 0; }
3.密码翻译
#include <bits/stdc++.h> using namespace std; int main() { string s; getline(cin, s); for (int i = 0; i < s.size(); ++i) { if (s[i] >= 'B' && s[i] <= 'Z') s[i]--; else if (s[i] == 'A') s[i] = 'Z'; else if (s[i] >= 'b' && s[i] <= 'z') s[i]--; else if (s[i] == 'a') s[i] = 'z'; } cout << s << endl; return 0; }
4.⽂字处理软件
#include <bits/stdc++.h> using namespace std; int main() { int q; string s; cin >> q >> s; while (q--) { int op; cin >> op; if (op == 1) { string str; cin >> str; s += str; cout << s << endl; } else if (op == 2) { int a, b; cin >> a >> b; s = s.substr(a, b); cout << s << endl; } else if (op == 3) { int a; string str; cin >> a >> str; s.insert(a, str); cout << s << endl; } else if (op == 4) { string str; cin >> str; int pos = s.find(str); cout << pos << endl; } } return 0; }
5.单词的⻓度
#include<bits/stdc++.h> using namespace std; int main() { string s; cin >> s; cout << s.size() << endl; return 0; }
6.单词翻转
#include<bits/stdc++.h> using namespace std; int main(){ string s; while(cin >> s){ reverse(s.begin(), s.end()); cout << s << endl; } return 0; }
7.判断字符串是否为回⽂
#include<bits/stdc++.h> using namespace std; int main() { string s; cin >> s; bool ok = true; int n = s.size(); for (int i = 0; i < n / 2; ++i) { if (s[i] != s[n - 1 - i]) ok = false; } cout << (ok ? "YES" : "NO") << endl; return 0; }
8.⼿机
#include<bits/stdc++.h> using namespace std; int main() { string s; cin >> s; for (int i = 0; i < s.size(); ++i) { if (s[i] >= '0' && s[i] <= '9') cout << s[i]; } return 0; }
9.⼝算练习题
#include<bits/stdc++.h> using namespace std; int main() { int a, b; char op; cin >> a >> op >> b; if (op == '+') cout << a + b << endl; else if (op == '-') cout << a - b << endl; else if (op == '*') cout << a * b << endl; return 0; }

日新闻