zoukankan      html  css  js  c++  java
  • 数组与字符串 1.2

    用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
    ", 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
  • 相关阅读:
    CRB and His Birthday(2015多校)
    B. Bear and Three Musketeers
    Uva657
    cas服务端改造
    有用的maven插件
    maven管理的非标准目录
    struts2中的action交由spring管理
    数据库分库
    linux内核系列之二_资源
    linux内核系列之一_工具
  • 原文地址:https://www.cnblogs.com/moderate-fish/p/3971431.html
Copyright © 2011-2022 走看看