参考网上的代码,谁知道有问题,修改了下,貌似可以了,VS2008上试验毫无鸭梨。
#include <iostream> using namespace std; //计算长度 size_t str_len(char *str_source) { size_t i = 0; while (*str_source++ != '\0') { ++i; } return i; } //翻转指定位置的字符串 char *reverse_str(char *str_source,size_t str_begin,size_t str_end) { size_t len = str_len(str_source); if(str_begin < 0 || str_end > len || str_end-str_begin > len) { throw runtime_error("error"); } char* str1 =new char[len+1]; strcpy(str1,str_source); for (; str_begin < str_end; ++str_begin,--str_end) { char temp = str_source[str_begin]; str1[str_begin] = str_source[str_end-1]; str1[str_end-1] = temp; } return str1; } //单词翻转 char *ReversalChar(char *strSouce) { size_t len = str_len(strSouce); //char* str1 = reverse_str(strSouce,0,len); size_t start = 0; char* str1 =new char[len+1]; str1 = reverse_str(strSouce,0,len); for (size_t i = 0; i < len; ++i) { if (strSouce[i] == ' ') { if (start == 0) { str1= reverse_str(str1,0,i); start = i+1; } else { str1 = reverse_str(str1,start,i); } } } return str1; } int main() { char* str_sourec = "sd qw zx lk"; cout << ReversalChar(str_sourec); }