69,382
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<string.h>
#include<malloc.h>
void shift(char* s,int n)
{
char* p;
char* q;
int len=strlen(s);
if(len==0)
return;
if(n<=0||n>=len)
return;
char* s2=(char*)malloc(len);
p=s;
q=s2+n%len;
while(*p)
{
*q++=*p++;
printf("%d,%d",q-s2,len);
if(q-s2>=len)
{
// *q=;
q=s2;
}
}
strcpy(s,s2);
free(s2);
}
int main()
{
char s[4];
scanf("%s",s);
shift(s,2);
printf("%s",s);
return 0;
}
#include<stdio.h>
#include<string.h>
#include<malloc.h>
void shift(char* s,int n)
{
char* p;
char* q;
int len=strlen(s);
if(len==0)
return;
if(n<=0||n>=len)
return;
char* s2=(char*)malloc(len+1);//开辟空间+1用来储存'\0'
p=s;
q=s2+n%len;
while(*p)
{
*q++=*p++;
if(q-s2>=len)
{
*q='\0';//字符串的结尾标志
q=s2;
}
}
//
strcpy(s,s2);
free(s2);
}
int main()
{
int i;
char s[4];
scanf("%s",s);
shift(s,2);
printf("%s",s);
/* for(i=0;i<4;i++)
{
printf("%c",s[i]);
}
*/
return 0;
}
这样改过来得
#include <string>
using namespace std;
string shift(const string& s, int n)
{
int n1=n%s.size();
string s1(s.begin()+n1,s.end());
s1 += s.substr(0,n1);
return s1;
}
int main()
{
string s;
cout << "input a string: " << endl;
cin >> s;
string s1=shift(s,2);
cout << s1 << endl;
return 0;
}
#include<stdio.h>
#include<string.h>
#include<malloc.h>
void shift(char* s,int n)
{
char* p;
char* q;
int len=strlen(s);
if(len==0)
return;
if(n<=0||n>=len)
return;
char* s2=(char*)malloc(len+1); //预留'\0'的空间
p=s;
q=s2+n%len;
while(*p)
{
*q++=*p++;
//printf("%d,%d",q-s2,len);
if(q-s2>=len)
{
// *q=;
q=s2;
}
}
*(s2+len) = '\0'; //结束符标志
strcpy(s,s2);
free(s2);
}
int main()
{
char s[5];
scanf("%s",s);
shift(s,2);
printf("%s",s);
return 0;
}
char* s2=(char*)malloc(len);//这一句应该为char* s2=(char*)malloc(len+1);