/*********************************************************************************************************
文件名称 : my_format.c
建立时间 : 2006-1-17 16:54
版权所有 : 东软股份大连分公司电信事业开发部
Author : 中介部.吴喆喆
文件描述 :
格式字符串 数字字符串 结果格式字符串
##### 12345 12345
##### 123 @@123
##,### 1234 @1,234
##,### 123 @@@123
##,### 1234567 34,567 错误, -1返回
#,###,###.## 123456789 1,234,567.89
#,###,###.## 1234567 @@@12,345.67
#,###,###.## 123 @@@@@@@@1.23
#,###,###.## 1 @@@@@@@@0.01
#,###,###.## 1 @@@@0.00001
修改记录 :
========================================================================================================
序号 修改日期 修改人 修改原因
*********************************************************************************************************/
#include"stdio.h"
#include <string.h>
#include <stdlib.h>
#include <limits.h>
int first_index_of(const char *string, char c)
{
int i = 0;
while (*string != '/0')
{
if (*string == c)
return i;
++string;
++i;
}
if (*string == '/0')
return -1;
}
int my_strpbrk(const char *string, const char *group)
{
int i = 0;
const char *p = group;
while (*string != '/0')
{
if (strchr(group, *string))
return i;
++string;
++i;
}
if (*string == '/0')
return -1;
}
int countchar(const char *string, char ch)
{
int i = 0;
const char *p = string;
while ((p = strchr(p, ch)) != NULL)
{
++i;
++p;
}
return i;
}
int format(char *f_string, const char *d_string)
{
char *bfs = f_string; /*对"#"号和特殊位置的","号的一些替换操作时要用到*/
char *bfs_4dot = f_string; /*对"."号的一些操作时要用到, @@@@@@@@@.@1要变成@@@@@@@@0.01*/
const char *bds = d_string;
char *temp;
int dis = 0;
int flag = 0;
if (!strlen(d_string)) /*数字字符串不能为空*/
return -1;
if (strlen(d_string) > countchar(f_string, '#')) /*数字字符串长度不能大于#的个数*/
return -1;
while (*f_string != '/0') /*不能用while(*f_string++) 因为到了/0时, 还会自增一次的*/
++f_string;
while (*d_string != '/0')
++d_string;
do /*要用do...while, 否则第一个字符输不出来*/
{
--f_string;
--d_string;
if (*f_string == ',' || *f_string == '.') /*保留,号和.号*/
{
++d_string; /*数字串保持原来的*/
continue;
}
*f_string = *d_string;
}while((f_string != bfs) && (d_string != bds));
/* printf("%s/n", bfs);
dis = first_index_of(bfs, ',') - my_strpbrk(bfs, "0123456789");
if (dis < 0)
flag = 1;
*/
/*对"#"号和特殊位置的","号的一些替换操作*/
while (*bfs != '/0')
{
/*有可能出现@@@@@,@@1.23这种情况, 所以把对","号位置的判断放在了循环里*/
dis = first_index_of(bfs, ',') - my_strpbrk(bfs, "0123456789"); /*注意: 这里要用bfs, 而不能用f_string, 因为f_string是bfs的一部分, 用f_string不全面*/
if (dis < 0)
flag = 1;
if (*bfs == '#') /*#都替换成@*/
*bfs = '@';
if (flag) /*符合调和的","号都替换成@*/
{
if (*bfs == ',') /**/
{
*bfs = '@';
flag = 0;
}
}
++bfs;
}
/*对"."号的一些操作时要用到, 针对@@@@@@@@@.@1*/
if (temp = strchr(bfs_4dot, '.'))
{
if (*--temp == '@')
*temp++ = '0'; /*@@@@@@@@0.@1, 此时指向"."号*/
while (*++temp != '/0') /*从"."号后面的第一位开始判断*/
{
if (*temp == '@')
*temp = '0';
}
//printf("%c/n", *--temp);
}
return dis;
}
main(void)
{
char fs[] = "#####.#####";
char ds[] = "1";
int i;
i = format(fs, ds);
printf("%s/n", fs);
//printf("%s/n%d/n", fs, i);
}