题目描述:
Life is short,you need Python!
听说python是一门神奇的语言,所以zzx毅然决然地走上了学习python的道路。
我们都知道 在C语言中,数组的下标是从0开始,从左到右,python也支持这种方式。
但是python还有另外一种表示方法,下标可以为负,从右到左,最后一个元素从-1开始,然后前面元素的下标依次减小,如下图所示:
下标用来访问单个元素,python还支持切片操作,切片是指通过指定下标范围和步长来获得子数组。
假定数组为S,切片用法如下:
S[start:end:step]表示取S中从start索引的位置起到end索引的位置,不包含end索引本身,每隔|step|-1个字符(||为绝对值),取一个字符。
假定数组长度为len。
若step > 0 表示上述操作从左至右进行
若start < -len start = - len
若end > len end = len
若step < 0 表示上述操作从右至左进行
若start >= len start = len - 1
若end < -len-1 end = -len - 1
如果S为”python”(字符串也是数组),S[0:4:1]表示的含义就是从下标0开始每取一个字符,下标+1接着取,当下标大于等于4的时候不能再取字符,所以得到的结果就是”pyth”,由于负下标的存在,你会发现[-6:4:1]、[-6:-2:1]、[0:-2:1]得到的结果同样是”pyth”
更多例子
[0:4:2] = “pt” [4:4:1] = “ ”(空) [-10:2:1]= “py” [3:10:1]= “hon”
[4:0:-1] = “ohty ” [-2:0:1] = “”(空) [4:0:-2] = “ot” [-2:0:-1]= “ohty ”
[-10:10:1]= “python” [10:-10:-1]= “nohtyp”
现在给出字符串和切片,请你把得到的结果告诉zzx。
输入:
首先是整数T (T<=50) 代表测试数据组数。
对于每组测试数据:
第一行是一个字符串S(只包含数字,大小写字母,长度不超过100);
第二行是一个整数Q(Q < 50),代表查询次数;
接下来是Q行输入查询参数, 格式为 [start:end:step] , start,end,step都为整数且step不为0,保证所有出现的整数不超过C语言的int范围。
输出:
对于每个查询输出一行,即python的S[start:end:step],如果查询结果为空,输出“#”.
样例输入:
2 python 5 [0:4:1] [-6:-2:1] [-2:0:-1] [10:-10:-2] [4:0:-2] WelcomeToHnustAcm117 3 [-1:-2:1] [-2:-1:1] [0:-6:1]
样例输出:
pyth pyth ohty nhy ot # 1 WelcomeToHnust
解题思路:
这题的难点并不大,数组会用的话,根据提示走就是了。
最大的难点大概就是输入了。
备用知识:%*c:读入一个字符,但忽略它(即不赋值给任何变量)
代码实现:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#include<string.h>
int main()
{
int t,start,end,step;
scanf("%d",&t);
while(t--)
{
char a[104];
getchar();
gets(a);
int n,len=strlen(a),i;
scanf("%d",&n);
while(n--)
{getchar();
int flag=0;
scanf("%*c%d:%d:%d%*c",&start,&end,&step);
if(step>0)
{
if(start<-len)start=-len;
if(end>len)end=len;
if(start<0)start=len+start;
if(end<0)end=len+end;
for(i=start; i<end; i=i+step)
{
printf("%c",a[i]);
flag=1;
}
if(flag==0)printf("#");
printf("\n");
}else
if(step<0)
{
if(start>=len)start=len-1;
if(end<-len-1)end=-len-1;
if(start<0)start=len+start;
if(end<0)end=len+end;
for(i=start; i>end; i=i+step)
{
printf("%c",a[i]);
flag=1;
}
if(flag==0)printf("#");
printf("\n");
}
}
}
}