数组与字符串 1.4

编写一个方法,将字符串中的空格全部替换为"%20"。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的"真实"长度。

示例

输入:"Mr John Smith"

输出:"Mr%20John%20Smith"

分析:先确定替换后的字符串的长度,然后从后往前处理输入字符串。

 1 #include <iostream>
 2 #include <fstream>
 3 #include <cstring>
 4 #include <assert.h>
 5 
 6 using namespace std;
 7 
 8 void replace( char *s );
 9 
10 int main( int argc, char *argv[] ) {
11     string data_file = "./1.4.txt";
12     ifstream ifile( data_file.c_str(), ios::in );
13     if( !ifile.is_open() ) {
14         fprintf( stderr, "cannot open file: %s\n", data_file.c_str() );
15         return -1;
16     }
17     const int BUFFER_SIZE = 1024;
18     char buffer[3*BUFFER_SIZE];
19     while( ifile.getline( buffer, BUFFER_SIZE ) ) {
20         cout <<buffer <<": ";
21         replace( buffer );
22         cout <<buffer <<endl;
23     }
24     ifile.close();
25     return 0;
26 }
27 
28 void replace( char *s ) {
29     int space = 0, slen = strlen(s);
30     for( int i = 0; i < slen; ++i ) {
31         if( s[i] == ' ' ) { ++space; }
32     }
33     int i = slen+1, j = slen + 2*space;
34     while( --i >= 0 ){
35         if( s[i] == ' ' ) {
36             s[j] = '0'; s[j-1] = '2'; s[j-2] = '%';
37             j -= 3;
38         } else {
39             s[j--] = s[i];
40         }
41     }
42     assert( j == -1 );
43     return;
44 }

测试文件

aa aa aa
nfsdfafds sdfsdf sdfsdf 
a a a a a a           
                asdfdsfs sdfdfs dfsdfsdfs
    aa dfs asdf asdf  sdf sdf   sdfs
Mr John Smith

 

posted on 2014-09-14 20:22  游不动の鱼  阅读(141)  评论(0编辑  收藏  举报