面试题目-华为

来源:互联网 发布:oa系统数据库表设计 编辑:程序博客网 时间:2024/05/22 21:11


题目要求:输入一个字符串,然后在输入一个整数,就是替换字符串的次数,然后依次输入需要替换的字符串……

例如:

输入:abcdefg

3

a->qwe

b->s

fg->abc

输出:qwescdeabc


[cpp] view plaincopyprint?
  1. //字符串替换   
  2. #include<iostream>  
  3. #include<vector>  
  4. #include<string>  
  5. #define max 100  
  6. using namespace std;  
  7.   
  8. void change(char str[],int count,int len_str,string buff,int jilu,int count_re_str)  
  9. {  
  10.     int j=0;  
  11.     int p=0;  
  12.       
  13.     char q[max];  
  14.   
  15.     for(int i=0;i<len_str;i++)  
  16.     {  
  17.         q[i]=str[i];//防止后面str改变影响元数组  
  18.     }  
  19.   
  20.     for(int i=jilu+count;i<len_str;i++)  
  21.     {  
  22.         str[jilu+count_re_str+p++]=q[i];  
  23.     }  
  24.     for(int i=jilu;i<jilu+count_re_str;i++)  
  25.     {  
  26.         str[i]=buff[j++];  
  27.     }  
  28.     str[jilu+count_re_str+p]='\0';  
  29. }  
  30.   
  31. void replace_str(char str[],int len_str,vector<string> restr,int index)  
  32. {  
  33.     bool flag=true;  
  34.     bool anquan=true;  
  35.     string s_str;  
  36.     string buff;  
  37.     s_str=restr[index];  
  38.     int jilu;  
  39.     int count=0;  
  40.     int count_re_str=0;  
  41.     int n=s_str.size();  
  42.     for(int i=0;i<n;i++)  
  43.     {  
  44.         if(s_str[i]>='a'&&s_str[i]<='z'&&anquan)  
  45.         {  
  46.             for(int j=0;j<len_str&&flag;j++)  
  47.             {  
  48.                 if(s_str[i]==str[j])  
  49.                 {  
  50.                     flag=false;  
  51.                     jilu=j;  
  52.                 }  
  53.             }  
  54.             count++;  
  55.         }  
  56.         else  
  57.         {  
  58.             if(anquan)  
  59.             {  
  60.                 i=i+2;  
  61.                 anquan=false;  
  62.             }  
  63.             if(s_str[i]>='a'&&s_str[i]<='z')  
  64.             {  
  65.                buff.push_back(s_str[i]);  
  66.                count_re_str++;  
  67.             }  
  68.         }  
  69.     }  
  70.     change(str,count,len_str,buff,jilu,count_re_str);  
  71. }  
  72.   
  73. int main()  
  74. {  
  75.     char str[max];  
  76.     vector<string> restr;  
  77.   
  78.     string s;  
  79.     gets(str);  
  80.       
  81.     int sum;  
  82.   
  83.     cout<<"请输入次数:";  
  84.     cin>>sum;  
  85.   
  86.     for(int i=0;i<sum;i++)  
  87.     {  
  88.         cin>>s;  
  89.         restr.push_back(s);  
  90.     }  
  91.   
  92.     for(int i=0;i<sum;i++)  
  93.     {  
  94.         int len_str=strlen(str);  
  95.         replace_str(str,len_str,restr,i);  
  96.     }  
  97.   
  98.     int q=0;  
  99.     while(str[q]!='\0')  
  100.     {  
  101.         cout<<str[q++];  
  102.     }  
  103.     cout<<endl;  
  104.   
  105.     system("pause");  
  106.     return 0;  
  107. }  

0 0