首页 > 其他 > 详细

数组与字符串 1.2

时间:2014-09-14 20:31:47      阅读:248      评论:0      收藏:0      [点我收藏+]

用C或C++实现void reverse( char* str )函数,即反转一个null结尾的字符串。

分析:先确定字符串的长度,然后从两端往中间遍历,同时交换两端的元素。

 1 #include <iostream>
 2 #include <fstream>
 3 #include <cstring>
 4 
 5 using namespace std;
 6 
 7 void reverse( char *str );
 8 
 9 int main( int argc, char *argv[] ) {
10     string data_file = "./1.2.txt";
11     ifstream ifile( data_file.c_str(), ios::in );
12     if( !ifile.is_open() ) {
13         fprintf( stderr, "cannot open file: %s\n", data_file.c_str() );
14         return -1;
15     }
16     char buffer[1000];
17     while( ifile.getline( buffer, 999 ) ) {
18         cout <<buffer <<": ";
19         reverse( buffer );
20         cout <<buffer <<endl;
21     }
22     ifile.close();
23     return 0;
24 }
25 
26 void reverse( char *s ) {
27     int slen = strlen( s );
28     for( int i = 0; i < slen/2; ++i ) {
29         swap( s[i], s[slen-i-1] );
30     }
31     return;
32 }

测试文件

a
aa
ab
abc
abcd
aaaaaaaaaaaaaaaaaaa

 

数组与字符串 1.2

原文:http://www.cnblogs.com/moderate-fish/p/3971431.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!