c++字符串反转操作

 

一 字符串按字节反转(this is a student ==> tneduts a si siht)
[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. /*************************************************************************  
  2.     > File Name: testStringByte.h 
  3.     > Author: qiaozp  
  4.     > Mail: qiaozongpeng@163.com  
  5.     > Created Time: 2014-9-30 11:21:15 
  6.     > Attention: this is a student ===> tneduts a si siht 
  7.  ************************************************************************/   
  8. #include <iostream>  
  9. #include <string.h>  
  10. using namespace std;  
  11.   
  12. void reverseByByte(char* p, char* e)  
  13. {  
  14.     //方法就是按位赋值到目的字符串  
  15.     int i = 0;  
  16.     int size = strlen(p);  
  17.     e[size] = '\0';  
  18.     while((--size) >= 0)  
  19.     {  
  20.         e[i++] = p[size];  
  21.     }  
  22. }  
  23.   
  24. int main()  
  25. {  
  26.     char* p = "you are a student!";  
  27.     char e[20] = {0};  
  28.     reverseByByte(p, e);  
  29.     cout << e << endl;  
  30. }  


 
二 字符串按单词反转(this is a student ==> student a is this)

 

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
    1. /*************************************************************************  
    2.     > File Name: testStringWord.h 
    3.     > Author: qiaozp  
    4.     > Mail: qiaozongpeng@163.com  
    5.     > Created Time: 2014-9-30 11:21:15 
    6.     > Attention: this is a student ===> student a is this 
    7. ************************************************************************/   
    8. #include <iostream>  
    9. #include <string.h>  
    10. using namespace std;  
    11.   
    12. void reverseByWord(char* p, char* e)  
    13. {  
    14.     //方法就是记录每个整的单词的开始和结束位置,然后拷贝到目标字符串  
    15.     int len = strlen(p);  
    16.     int end = len;  
    17.     int start = 0;  
    18.     memset(e, 0, len);  
    19.   
    20.     while(len > 0)  
    21.     {  
    22.         end = len;  
    23.         while ((p[len - 1] != ' ') && (len > 0))  
    24.         {  
    25.             --len;  
    26.         };  
    27.         start = len--;  
    28.         strncpy(e + strlen(e), p + start, end - start);  
    29.         e[strlen(e)] = ' ';  
    30.   
    31.     }  
    32.     e[strlen(e) - 1] = '\0';      //多出一个空格  谢谢二楼的提醒   
    33. }  
    34.   
    35. int main()  
    36. {  
    37.     char* p = "you are a student!";  
    38.     char e[20] = {0};  
    39.     reverseByWord(p, e);  
    40.     cout << e << endl;  
    41. }  

 

posted on 2016-07-18 10:56  c++kuzhon  阅读(371)  评论(0)    收藏  举报

导航