[隨堂測驗]substr()函式&find() 函式&replace() 函式
本帖最後由 李泳霖 於 2024-8-22 13:48 編輯
- cout<<"請輸入你需要的功能:"<<endl;
- cout<<"(1)字串擷取(2)尋找字母或字串位置(3)取代功能:";
- cout<<"請輸入字串:";
- cout<<"請輸入起始編號:";
- cout<<"需要抓取幾個字:";
- cout<<"請勿亂輸入"<<endl;
- cout<<"請輸入字串:";
- cout<<"請輸入要尋找的字元或英文字母:";
- cout<<"找不到此字元或字母"<<endl;
- cout<<"字元"<<___<<"的索引位置(由前往後找):"<<___<<endl;
- cout<<"請輸入字串:";
- cout<<"請輸入要從哪個編號開始取代:";
- cout<<"查無此編號"<<endl;
- cout<<"請輸入取代幾個:";
- cout<<"不可取代"<<endl;
- cout<<"請輸入取代幾個:";
- cout<<"請輸入取代為哪個字元或字串:";
- cout<<"無此功能"<<endl;
複製代碼- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
- int a,s,r;
- int res;
- char c;
- string str,s1;
- re:
- cout<<"請輸入您需要的功能:"<<endl;
- cout<<"(1)字串擷取(2)尋找字母或字元位置(3)取代功能:";
- cin>>a;
- switch(a)
- {
- case 1:
- cout<<"請輸入字串:";
- cin>>str;
- cout<<"請輸入起始編號:";
- cin>>s;
- cout<<"需要抓取幾個字:";
- cin>>r;
- if(r>=0 && r+s<=str.length())
- cout<<str.substr(s,r)<<endl;
- else
- cout<<"請勿亂輸入!"<<endl<<endl;
- break;
- case 2:
- cout<<"請輸入字串:";
- cin>>str;
- cout<<"請輸入要尋找的字元或英母:";
- cin>>c;
- res=str.find(c);
- if(res==-1)
- cout<<"找不到此字元或字母"<<endl<<endl;
- else
- cout<<"字元"<<c<<" 的索引位置 (由前往後查找): "<<res<<endl;
- break;
- case 3:
- cout<<"請輸入字串:";
- cin>>str;
- cout<<"請輸入要從哪個編號開始取代:";
- cin>>s;
- if(s>str.length())
- {
- cout<<"查無此編號"<<endl<<endl;
- goto re;
- }
- cout<<"請輸入取代幾個:";
- cin>>r;
- if(s+r>str.length())
- {
- cout<<"不可取代"<<endl<<endl;
- goto re;
- }
- cout<<"請輸入取代為什麼字元或字串:";
- cin>>s1;
- cout<<str.replace(s,r,s1)<<endl;
- break;
- default:
- cout<<"請勿亂輸入"<<endl;
- }
- cout<<endl;
- goto re;
- return 0;
- }
複製代碼- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
- re:
- int n,u,m;
- string s,t;
- cout<<"請輸入你需要的功能:"<<endl;
- cout<<"(1)字串擷取(2)尋找字母或字串位置(3)取代功能:";
- cin>>n;
- if(n==1){
- cout<<"請輸入字串:";
- cin>>s;
- cout<<"請輸入起始編號:";
- cin>>u;
- cout<<"需要抓取幾個字:";
- cin>>m;
- if(u+m>s.length())
- cout<<"請勿亂輸入"<<endl;
- else
- cout<<s.substr(u,m)<<endl;
- }
- else if(n==2){
- cout<<"請輸入字串:";
- cin>>s;
- cout<<"請輸入要尋找的字元或英文字母:";
- cin>>t;
- int q=s.find(t);
- if(q==-1)
- cout<<"找不到此字元或字母"<<endl;
- else
- cout<<"字元"<<t<<"的索引位置(由前往後找):"<<q<<endl;
- }
- else if(n==3){
- cout<<"請輸入字串:";
- cin>>s;
- cout<<"請輸入要從哪個編號開始取代:";
- cin>>u;
- if(u>s.length())
- cout<<"查無此編號"<<endl;
- else if(u+m>s.length()){
- cout<<"請輸入取代幾個:";
- cin>>m;
- cout<<"不可取代"<<endl;
- }
- else{
- cout<<"請輸入取代幾個:";
- cin>>m;
- cout<<"請輸入取代為哪個字元或字串:";
- cin>>t;
- cout<<s.replace(u,m,t)<<endl;
- }
- }
- else
- cout<<"無此功能"<<endl;
- cout<<endl;
- system("pause");
- system("cls");
- goto re;
- return 0;
- }
複製代碼 |
附件:
您需要登錄才可以下載或查看附件。沒有帳號?註冊