字符串翻转(C++)
1.字符串原地翻转,"abc"->"cba":
int str_reverse(string &str,int first,int last) { if(first>last) return -1;//对比失败 else if(first==last) return 0;//对比完成 if(str.length()<last) return -1; char t=str[first]; str[first]=str[last]; str[last]=t; return str_reverse(str,++first,--last); }
2.字符串分单词翻转,"cat is tom"->"tom is cat":
string str_word_reverse(string str) { int i=0,j=0,p=0,k=0,len=str.length(); string str_tmp(len,NULL); k=len-1; while(i<len&&j<len) { while(j<len&&' '!=str[j]) j++; p=j; while(i<j) { str_tmp[k--]=str[--j]; } if(k>=0)str_tmp[k]=' ';//空格 k--; i=j=p+1; } return str_tmp; }