本题要求编写函数,将输入字符串的前3个字符移到最后。
函数接口定义:
void Shift( char s[] );
其中char s[]
是用户传入的字符串,题目保证其长度不小于3;函数Shift
须将按照要求变换后的字符串仍然存在s[]
里。
裁判测试程序样例:
#include <stdio.h>
#include <string.h>
#define MAXS 10
void Shift( char s[] );
void GetString( char s[] ); /* 实现细节在此不表 */
int main()
{
char s[MAXS];
GetString(s);
Shift(s);
printf("%s\n", s);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
abcdef
输出样例:
defabc
解法1:用字符串函数
#include <stdio.h>
#include <string.h>
#define MAXS 10
void Shift( char s[] );
void GetString( char s[] ); /* 实现细节在此不表 */
int main()
{
char s[MAXS];
gets(s);
Shift(s);
printf("%s\n", s);
return 0;
}
/* 你的代码将被嵌在这里 */
void Shift( char s[] )
{
int n,i,j;
char str2[MAXS],str1[MAXS];
strcpy(str1,s); //str1的空间必须大于等于s的空间,如果小,会造成缓冲溢出,系统报错
str1[3] = '\0';//字符串第4个字符换成结束符 ,相当于只复制前3个和结束符
strcpy(str2,s+3);//字符串的前3个字符后面的字符
strcat(str2,str1);
strcpy(s,str2);
}
解法2:用数组的思想
#include <stdio.h>
#include <string.h>
#define MAXS 10
void Shift( char s[] );
void GetString( char s[] ); /* 实现细节在此不表 */
int main()
{
char s[MAXS];
gets(s);
Shift(s);
printf("%s\n", s);
return 0;
}
/* 你的代码将被嵌在这里 */
void Shift( char s[] )
{
int n,i,j;
char str2[MAXS],str1[4];//str1需存放3个字符串 和一个结束符
n = strlen(s);//字符串长度
for(i=0;i<3;i++){//字符串的前3个字符
str1[i] = s[i];
}
str1[i]='\0';//完整字符串
j = 0;
for(i=3;i<n;i++){//字符串的前3个字符后面的字符
str2[j] = s[i];
j++;
}
str2[j]='\0';//完整字符串
strcat(str2,str1);
strcpy(s,str2);
}