现在的位置: 首页 > 综合 > 正文

每日一练(1)

2013年01月30日 ⁄ 综合 ⁄ 共 1703字 ⁄ 字号 评论关闭

题目:把给定的字符串以单词的方式反序,其中,给定的子串不倒转。

比如:s[] = "The quick brown fox jumps over the lazy dog"; 子串: sub[] = "brown fox";

结果应该是:dog lazy the over jumps brown fox quick The.

  1. #include<iostream>
  2. using namespace std;
  3. void reverse(char* s);
  4. void func(char* s, char* sub);
  5. int main()
  6. {
  7.     char s[] = "The quick brown fox jumps over the lazy dog";
  8.     char sub[] = "The quick";    
  9.     func(s, sub);
  10.     
  11.     system("pause");
  12.     return 0; 
  13. }
  14. void reverse(char* s, char * s1)
  15. {    
  16.     int n = strlen(s)-1;
  17.     
  18.     for(int i=n; i>=0; i--)
  19.     {
  20.         if(s[i]==' ')
  21.         {
  22.             int temp = i+1;
  23.             strcat(s1, s+temp);
  24.             strcat(s1, " "); 
  25.             s[i] = '/0';       
  26.         }
  27.     }
  28.     strcat(s1, s);
  29.     strcat(s1, "/0");
  30. }
  31. void func(char* s, char* sub)
  32. {
  33.     int sizeof_s = strlen(s)+1;
  34.     char* s1 = new char[sizeof_s]; 
  35.     s1[0] = '/0';
  36.     
  37.     char* s_0 = new char[strlen(s)+1];
  38.     strcpy(s_0, s);
  39.     reverse(s_0, s1);
  40.     cout << "s1 = " << s1 << endl; 
  41.     
  42.     int sizeof_sub = sizeof(sub)+1;
  43.     char* sub1 = new char[sizeof_sub]; 
  44.     sub1[0] = '/0';
  45.     
  46.     char* sub_0 = new char[strlen(sub)+1];
  47.     strcpy(sub_0, sub);
  48.     reverse(sub_0, sub1);
  49.     cout << "sub1 = " << sub1 << endl; 
  50.     int s_length = strlen(s1);
  51.     int sub_length = strlen(sub1);
  52.     
  53.     for(int i=0; i<s_length; i++)
  54.     {
  55.         if(s1[i]==sub1[0] && s1[i]!=' ')
  56.         {
  57.             for(int j=1; j<strlen(sub1); j++)
  58.             {
  59.                 if(s1[i+j]!=sub1[j])
  60.                 {
  61.                     break;                      
  62.                 }        
  63.                 cout << sub ;
  64.                 i = i+sub_length;
  65.             }                  
  66.         }   
  67.         cout << s1[i] ;        
  68.     }
  69.     
  70.     delete[] s1;
  71.     delete[] s_0;
  72.     delete[] sub1;
  73.     delete[] sub_0;
  74. }

抱歉!评论已关闭.