字符串的展开
如果在输入的字符串中,含有类似于“d-h”或者“4-8”的字串,我们就把它当作一种简写,输出时,用连续递增的字母或数字串替代其中的’-’.
即“d-h”输出为“defgh”
“4-8”输出为“45678"
现在编写一个函数并在主函数调用能够实现以下逻辑:
遇到以下情况需要做字符串的展开:
在输入的字符串中,出现了减号“-”,且减号两侧同为小写字母或同为数字。 本帖最后由 jackz007 于 2021-11-7 02:04 编辑
这个代码太烧脑了!
#include <stdio.h>
bool alpha(char c)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ;
}
bool upper(char c)
{
return c >= 'A' && c <= 'Z' ;
}
bool lower(char c)
{
return c >= 'a' && c <= 'z' ;
}
bool digit(char c)
{
return c >= '0' && c <= '9' ;
}
bool check(char s[])
{
int m ;
bool r = false ;
for(m = 0 ; s && m < 3 ; m ++) ;
if(m > 2 && s == '-') {
if((alpha(s) && alpha(s)) || (digit(s) && digit(s))) {
if((upper(s) && upper(s)) || (lower(s) && lower(s))) {
r = true ;
} else if(digit(s) && digit(s)) {
r = true ;
}
}
}
return r ;
}
char * expand(char s[])
{
int c , d , e , i , k , m, n ;
bool f ;
for(m = 0 ; s ; m ++) ;
for(n = m , f = false , i = 0 ; i < n - 2 ; i ++) {
if(check(& s)) {
e = (s > s) ? s - s + 1 : s - s + 1 ;
if(e > 3) {
for(k = 0 ; k < n - i - 1 ; k ++) s = s ;
n += e - 3 ;
} else if(e < 3) {
for(k = 0 ; k < n - i - 1 ; k ++) s = s ;
n -= 3 - e ;
}
if(e > 2) {
d = (s > s) ? 1 : -1 ;
for(c = s , k = 0 ; k < e ; c += d , k ++) s = c ;
}
i += e - 1 ;
}
}
return s ;
}
int main(void)
{
char s = {0} ;
gets(s) ;
printf("%s\n" , expand(s));
}
编译、运行实况:
D:\00.Excise\C>g++ -o x x.c
D:\00.Excise\C>x
12345K-Abcdefg-x123-9abcdef9-1
12345KJIHGFEDCBAbcdefghijklmnopqrstuvwx123456789abcdef987654321
D:\00.Excise\C>
页:
[1]