字符串做加一运算的有关问题!总结了一下!大家指点
字符串做加一运算的问题!~~~~总结了一下!大家指点~
刚才的帖子得到了很多人的启发 谢谢了~
我刚刚写了一个函数 大家帮忙看看 还是一个3字符的字符串
例如: "R12 "+1 == "R13 " "R99 "+1== "S00 " "R19 "+1== "R20 "
加1后返回字符串 ~~~
char *addsn(char *a_sn)
{
int j;
char *Error= "NG ";
for(j=2;j <=0;j--)
{
if(*(a_sn+j)> = 'a '&&*(a_sn+j) <= 'z ')
{
if(*(a_sn+j)== 'z ')
return Error;
else
{
*(a_sn+j)=(*(a_sn+j)+1)% 'z ';
return a_sn;
}
}
if(*(a_sn+j)> = 'A '&&*(a_sn+j) <= 'Z ')
{
if(*(a_sn+j)== 'Z ')
return Error;
else
{
*(a_sn+j)=(*(a_sn+j)+1)% 'Z ';
return a_sn;
}
}
if(*(a_sn+j)> = '0 '&&*(a_sn+j) <= '9 ')
{
if(*(a_sn+j)== '9 ')
*(a_sn+j)= '0 ';
else
{
*(a_sn+j)=(*(a_sn+j)+1)% '9 ';
return a_sn;
}
}
}
return Error;
}
此函数还有什么不足的 大家指导下~
------解决方案--------------------
为啥不写个可以处理任意位数的!
#include <stdio.h>
#include <string.h>
void string_inc(char *s)
{
char *p;
char c;
p = s;
for (p = s; *p; p++)
;
c = 0;
p--;
(*p)++;
for (; p > = s; p--)
{
*p +=c;
switch (*p)
{
case '9 ' + 1:
*p = '0 ';
c = 1;
break;
case 'z ' + 1:
c = 1;
*p = 'a ';
break;
case 'Z ' + 1:
c = 1;
*p = 'A ';
break;
default:
c = 0;
}
}
}
int main(void)
{
char *ss[] = { "R12 ", "R99 ", "R19 ", "R12 ", "Rz9 ", "Ra9 "};
char s[4];
int i, n;
n = sizeof(ss)/sizeof(ss[0]);
for (i = 0; i < n; i++)
{
strcpy(s, ss[i]);
printf( "%s + 1 = ", s);
string_inc(s);
printf( "%s\n ", s);
}
return (0);
}
刚才的帖子得到了很多人的启发 谢谢了~
我刚刚写了一个函数 大家帮忙看看 还是一个3字符的字符串
例如: "R12 "+1 == "R13 " "R99 "+1== "S00 " "R19 "+1== "R20 "
加1后返回字符串 ~~~
char *addsn(char *a_sn)
{
int j;
char *Error= "NG ";
for(j=2;j <=0;j--)
{
if(*(a_sn+j)> = 'a '&&*(a_sn+j) <= 'z ')
{
if(*(a_sn+j)== 'z ')
return Error;
else
{
*(a_sn+j)=(*(a_sn+j)+1)% 'z ';
return a_sn;
}
}
if(*(a_sn+j)> = 'A '&&*(a_sn+j) <= 'Z ')
{
if(*(a_sn+j)== 'Z ')
return Error;
else
{
*(a_sn+j)=(*(a_sn+j)+1)% 'Z ';
return a_sn;
}
}
if(*(a_sn+j)> = '0 '&&*(a_sn+j) <= '9 ')
{
if(*(a_sn+j)== '9 ')
*(a_sn+j)= '0 ';
else
{
*(a_sn+j)=(*(a_sn+j)+1)% '9 ';
return a_sn;
}
}
}
return Error;
}
此函数还有什么不足的 大家指导下~
------解决方案--------------------
为啥不写个可以处理任意位数的!
#include <stdio.h>
#include <string.h>
void string_inc(char *s)
{
char *p;
char c;
p = s;
for (p = s; *p; p++)
;
c = 0;
p--;
(*p)++;
for (; p > = s; p--)
{
*p +=c;
switch (*p)
{
case '9 ' + 1:
*p = '0 ';
c = 1;
break;
case 'z ' + 1:
c = 1;
*p = 'a ';
break;
case 'Z ' + 1:
c = 1;
*p = 'A ';
break;
default:
c = 0;
}
}
}
int main(void)
{
char *ss[] = { "R12 ", "R99 ", "R19 ", "R12 ", "Rz9 ", "Ra9 "};
char s[4];
int i, n;
n = sizeof(ss)/sizeof(ss[0]);
for (i = 0; i < n; i++)
{
strcpy(s, ss[i]);
printf( "%s + 1 = ", s);
string_inc(s);
printf( "%s\n ", s);
}
return (0);
}