切換字符串中的每個單詞對(「ab cd ef gh ijk」變爲「 cd ab gh ef ijk「)在C++中沒有任何庫函數。在c/C++中切換字符串中的每一對單詞(「ab cd ef gh ijk」變爲「cd ab gh ef ijk」)
int main(){
char s[]="h1 h2 h3 h4";//sample input
switch_pair(s);
std::cout<<s;
return 0;
}
char * switch_pair(char *s){
char * pos = s;
char * ptr = s;
int sp = 0;//counts number of space
while(*pos){
if(*pos==' ' && ++sp==2){ //if we hit a space and it is second space then we've a pair
revStr_iter(ptr,pos-1);//reverse the pair so 'h1 h2' -> '2h 1h'
sp=0;//set no. of space to zero to hunt new pairs
ptr=pos+1;//reset ptr to nxt word after the pair i.e. h3'
}
pos++;
}
if(sp==1) //tackle the case where input is 'h1 h2' as only 1 space is there
revStr_iter(ptr,pos-1);
revWord(s); //this will reverse each individual word....i hoped so :'(
return s;
}
char* revStr_iter(char* l,char * r){//trivial reverse string algo
char * p = l;
while(l<r){
char c = *l;
*l = *r;
*r = c;
l++;
r--;
}
return p;
}
char* revWord(char* s){//this is the villain....need to fix it...Grrrr
char* pos = s;
char* w1 = s;
while(*pos){
if(*pos==' '){//reverses each word before space
revStr_iter(w1,pos-1);
w1=pos+1;
}
pos++;
}
return s;
}
輸入 - H1 H2 H3 H4
預期 - H2 H1 H4 H3
實際 - H2 H1 H3 4H
可以在任何高尚的怪胎靈魂的幫助PLZ:(((
如果列表中包含奇數個單詞,會發生什麼?或者如果一對單詞由多個空格分隔? – 2011-03-03 21:30:38
在奇數字的情況下...最後一個奇數字保持原樣..所以h1 h2 h3將作爲h2 h1 h3輸出 多個空格或製表符可以通過將if條件增加指針,直到我們得到一個空格... – 2011-03-03 21:33:03
連續空格怎麼樣? I.e .:'「h1 h2」'? –
MSN
2011-03-03 23:19:02