1. 函数expand(s1,s2),将字符串s1中类似a-z的字符串在s2中扩展为等价abc...xyz完整序列
#include<stdio.h>
void expand(char s1[], char s2[])
{
char c;
int i, j;
i = j = 0;
while( (c = s1[i++]) != '\0')
{
if( s1[i] == '-' && s1[i+1] >= c)
{
i++;
while( c < s1[i])
s2[j++] = c++;
}
else
s2[j++] = c;
}
s2[j] = '\0';
}
int main()
{
char s1[20],s2[100];
scanf("%s%*c",s1);
expand(s1,s2);
printf("string = %s", s2);
getchar();
return 1;
}
2. itoa(n,s)函数的改进,一般我们编的不能处理n为负数最大值的情况,一下是函数的改进与对比(3-4)
#include<stdio.h>
#include<string.h>
#include<limits.h>
#define abx(x) ((x) < 0 ? -(x):(x))
void reverse(char s[])
{
int c, i, j;
for( i = 0, j = strlen(s) - 1; i < j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
void itoa1(int n, char s[])
{
int i, sign;
i = 0;
if( (sign = n) < 0)
n = -n; //当n为负数最大数是不成立的,因为整数的最大数字 = | 负数最大值| -1
do
{
s[i++] = n % 10 + '0';
}while( (n /= 10) > 0);
if(sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
void itoa2(int n, char s[])
{
int i, sign;
i = 0;
sign = n;
do
{
s[i++] = abs(n % 10) + '0';
}while( (n /= 10) != 0);
if(sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
int main()
{
char s[20];
int n = INT_MIN;
itoa1(n,s);
printf("s1 = %s\n",s);
itoa2(n,s);
printf("s2 = %s\n",s);
getchar();
return 1;
}
3. 函数itob(n,s,b)是把n的b进制表示以字符串的形式存储在s中(3-5)
#include<stdio.h>
#include<limits.h>
#include<string.h>
#define abx(x) ((x) < 0 ? -(x):(x))
void inverse(char s[])
{
int i, j, c;
for(i = 0, j= strlen(s) - 1; i < j; i++,j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
void itob(int n, char s[], int b)
{
int i, j, sign;
i = 0;
sign = n;
do
{
j = abs(n % b);
s[i++] = ( j <= 9) ? j + '0' : j + 'a' - 10;
}while( (n /= b) != 0);
if(sign < 0)
s[i++] = '-';
s[i] = '\0';
inverse(s);
}
int main()
{
int n;
char s[20];
n = INT_MIN;
itob(n, s, 16);
printf("result = %s\n", s);
getchar();
return 1;
}