試以 replace() 函式,將字串中的目標對象以特定字串取代。
<string> 標頭檔與 <algorithm> 標頭檔皆有提供 replace() 函式,但其用法與效果略有不同。- #include<iostream>
- #include<cstdlib>
- #include<string>
- #include<algorithm>
- using namespace std;
- int main()
- {
- string str1="honolulu";
- cout<<str1.replace(5,1,"a")<<endl; //honolalu
-
- string str2="honolulu";
- cout<<str2.replace(str2.find("u"),1,"a")<<endl; //honolalu
-
- string str3="honolulu";
- replace(str3.begin(),str3.end(),'u','a');
- cout<<str3<<endl; //honolala
-
- system("pause");
- return 0;
- }
複製代碼 |