2017-03-04 52 views
-5

我已經嘗試過,但我無法向後打印中間單詞!如何更改字符數組的中間字向後

ex。輸入=這個詞落後;輸出=此卓爾向後

char chai[80]; 
int cont=0; 
cout << "Enter odd string words to reverse the one of the middle: "; 
cin.getline(chai,80); 
for(int x=0; x< strlen(chai) ;++x) 
{ 
    if(chai[x]==' ') 
    ++cont;   
} 

任何建議所理解的,

+0

可以舉個例子? – 2017-03-04 21:00:53

+0

ex。輸入=這個詞落後; output = this drow backward –

+0

你可以在JAVA中使用'split()'方法,使用空格作爲分隔符,然後嘗試訪問數組中的中間並反轉它,然後用新內容重建字符串^ _ ^ – 2017-03-05 13:09:36

回答

0
#include <iostream> 
#include <string.h> 
using namespace std; 

int main() 
{ 
    char chai[80]; 
    cout<<"introduce your phrase with an odd number of words"<<endl; 
    cin.getline(chai,80); 
    int cont=0; 
    char c; 
    cout<<endl; 
    cout<<"Frase:"<<endl; 

    for(int x=0;x<=strlen(chai)-1;++x)//count the words 
    { 
     if(chai[x]==' ') 
     { 
      ++cont; 
      cout<<chai[x];//spaces will help to find the word in the middle 
     } 
     else 
      cout<<chai[x]; 
    } 
    cout<<endl; 
    cout<<endl; 
    if(cont%2!=0) 
    { 
     cout<<"It is necessary to introduce an odd number of words"; 
     return 0; 
    } 
    cout<<endl; 
    cout<<endl; 
    int aux=cont/2; 
    int cont_dos=0; 
    int cont_tres=0; 
    cout<<"***It would be:***"<<endl; 
    for(int i=0;i<=strlen(chai)-1;++i) 
    { 
     if(chai[i]==' ') 
     { 
      cont_dos++; 
      if(cont_dos==aux) 
      { 
       for (int j=strlen(chai)-1;j!=0;--j) 
       { 
        if(chai[j]==' ') 
        { 
         cont_tres++; 
         cout<<chai[j]; 
        } 
        if(cont_tres==aux) 
        { 
         cout<<chai[j]; 
         ++i; 
         if(cont_tres>aux) 
         { 
          ++i; 
          cout<<chai[i]; 
          if(i==strlen(chai)-1) 
          { 
           return 0; 
          } 
         } 
        } 
        //if(cont_tres>aux) 
       } 
      } 
      else 
       cout<<chai[i]; 
     } 
     else 
      cout<<chai[i]; 
    } 


    return 0; 
} 
相關問題