1. 程式人生 > >C++ 基礎題(一)

C++ 基礎題(一)

輸入格式:
Xi’an Institute of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology. The Institute is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
end (表示結束)
Institute (第一個字串,要求用第二個字串替換)
University (第二個字串)
輸出格式:
Xi’an University of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.The University is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int replace_string(vector<string> &str,const string &str1,const string &str2)
{

    for(int i=0; i<str.size(); i++)
    {
        if((str.at(i)).compare(str1)==0)
        {
            str.at(i)=str2;
        }
    }

    return 0;
}

int replace_str(string &str,const string &str1,const string &str2)
{
    int p=str.find(str1);//-1  pos
    while(p!=-1)
    {
        cout<<p<<endl;
        str.replace(p,str1.length(),str2);
        p=str.find(str1,p+1);
    }
}
int main()
{
   /* vector<string> str;
    str.clear();
    string str1;
    string str2;
    string input;
    cin>>input;
    while(input.compare("end")!=0)
    {
        str.push_back(input);
        cin>>input;
    }
    cin>>str1;
    cin>>str2;
    replace_string(str,str1,str2);
    for(int i=0;i<str.size();i++)
        cout<<str.at(i)<<" ";
    */
    string str;
    string str1,str2,str3;
    getline(cin,str1,'\n');
    while(1)
    {
        if(str1.compare("end")==0)
            break;
        str+=str1;
        getline(cin,str1,'\n');
    }
    cin>>str2;
    cin>>str3;
    replace_str(str,str2,str3);
    cout<<str<<endl;
}


輸入格式:
例如:輸入
c:\windows\winhelp.exe
輸出格式:
c:\windows (目錄路徑)
winhelp.exe (檔名)
#include <iostream>
#include <string>
using namespace std;

int spa(const string & str,string & dec,string &name)
{
    int f=str.find_last_of('\\');
    if(f==-1)
    {
        f=str.find_last_of('/');
        if(f==-1) return -1;
    }
    name.append(str,f+1,str.size()-f+1);
    dec.append(str,0,f-1);
}

int main()
{
    string str,dec,name;
    cin>>str;
    spa(str,dec,name);
    cout<<dec<<endl<<name<<endl;
    return 0;
}