2009年12月18日 星期五

字串分行且左右對齊

 
為使編排較美觀,我根據單字長度,由短而長依次調整字距:
//以 a 為 primal key, b 跟著 a 一塊兒做 sorting

void sort (int* a, int* b, int n)
{
   int t, u, i, j, g;   
   for (g=n; g>0; g= (g>1 && g<5)? 1: 5*g/11)
       for (i=g; i<n; ++i){        
           t = a[i];
           u = b[i];
           for (j=i; j>=g && t<a[j-g]; j-=g) {
                a[j] = a[j-g];
                b[j] = b[j-g];
           }
           a[j] = t;
           b[j] = u;
       }
}
                                 
int main (/* -.. .- ...- .. -.. -.. .-.  */)
{
    int   index[512];               //反向索引
    int   wlen [512];               //單詞長度
    int   stuff[512];               //填充空白數   
    int   i = 0, nStuff;            //i 為累計單詞數
    int   j, n, len = 0; 
    int   width = 40;               //width = 指定欄寬  
                                    //欄寬需大於最大單詞長度!
    char  in[] =
    "In computing, C is a general-purpose, block structured,"
    " procedural, imperative computer programming language "
    "developed in 1972 by Dennis Ritchie at the Bell Telephone"
    "Laboratories for use with the Unix operating system.";

    char *s = in, *p = in;
    char out[4096], *o = out;

    while (*p)
    {     
        stuff[i] = 0;
        index[i] = i;
        for (n=0; *p && ' '!=*p; ++n, ++p);     //n = 單詞長度
        if (' '==*p) { ++p; ++n; }
        len += (wlen[i] = n);                   //累計列長
                  
        if (len > width)
        {         
            nStuff = width - len + n;           //算總填充數
            sort (wlen, index, i-1);            //根據字長排序
            j = 0;
            while (nStuff--) {                  //算個別填充數   
                ++stuff[j];
                if (++j >= i-1) j = 0;
            }
            sort (index, stuff, i-1);           //將 stuff 照
                                                //原始字序排列
            for (j=0; j<i-1; ++j) {
                while (' '!=*s) *o++ = *s++;
                do *o++ = ' '; while (stuff[j]--); ++s;                 
            }
            while (*s && ' '!=*s) *o++ = *s++;
            if (' ' == *s) { *o++ = '\n'; ++s; }
                     
            index[0] = stuff[0] = 0;
            wlen[0]  = len = n;
            i = 0;            
        }               
        ++i;
    }
    for (p-=len; *p; *o++ = *p++); *o++ = *p++;
         
    puts (out);
  
    return system ("pause");   
}

寬度為 40 時,輸出:
In computing, C  is a  general-purpose,
block      structured,      procedural,
imperative     computer     programming
language developed in  1972  by  Dennis
Ritchie   at    the    Bell   Telephone
Laboratories  for  use  with  the  Unix
operating system.

沒有留言:

張貼留言