现在的位置: 首页 > 综合 > 正文

字符串中单词逆序

2012年01月12日 ⁄ 综合 ⁄ 共 1236字 ⁄ 字号 评论关闭
/**//*
 *     将字符串中单词出现次序逆序。
 *    "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 
= 0;
    
while ( i < size/2 ) {
        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  1234   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;
}

抱歉!评论已关闭.