壁立千仞,无欲则刚

字符串中单词逆序

将字符串中单词出现次序逆序。

对字符串扫描两次,第一次全体逆序,第二次以单词为单位逆序

/*

 *    "123 45 6"  --->>    "6 45 123"     
 
*/

#include 
<stdio.h>
#include 
<stdlib.h>
#include 
<string.h>

char* reverse_string( char* p, unsigned int size )
{
    
char            tmp;
    unsigned 
int    i; 

    
if ( p == NULL || size == 0 || size == 1 )
        
return NULL;

    i 
= size/2;
    
while ( i > 0 ) {
        tmp            
= p[i];
        p[i]        
= p[size-1-i];
        p[size
-1-i]    = tmp;
        i
--;
    }

    
return p;
}

int main( void )
{
    
char buf[100= "  1234567 1  123   4 56 ";
    unsigned 
int buf_size;
    unsigned 
int i;
    unsigned 
int j;

    buf_size 
= strlen( buf );

    printf(
"old string:\n%s\n", buf );
    reverse_string( buf, buf_size );
    printf(
"reversed first time:\n%s\n", buf );

    i 
= 0;
    
while ( i < buf_size ) {
        
//    skip spaces
        while ( buf[i] == ' ' && buf[i] != '\0' ) {
            i
++;
        }
        j 
= i;

        
//    find nearest space
        while ( buf[i] != ' ' && buf[i] != '\0' ) {
            i
++;
        }

        
//    now j point to the first character of 
        
//    current word and i point to the nearest space
        reverse_string( &buf[j], i-j );
    }
    printf(
"reversed string:\n%s\n", buf );

    
return 0;
}

posted on 2008-07-11 22:02 bynow 阅读(250) 评论(1)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理


<2026年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿

文章档案

搜索

最新评论