例:s指向字符串"abcdef",经过移动后s指向的字符串为"defabc"
方法一:
#include <stdio.h>
void Shift (char *str){
char str1[3] = {*str, *(str+1), *(str+2)};
int i,j;
for(i=3; *(str+i); i++){
*(str+(i-3)) = *(str+i);
}
for(j=i-3,i=0; i<3; i++){
*(str+(j++)) = str1[i];
}
}
void main () {
char str[100];
printf("请输入一个字符串:");
gets(str);
Shift(str);
printf("移动后:%s", str);
}
方法二:
注意:宏定义处要指定字符个数
#include <stdio.h>
#define MAXS 6
void Shift( char *s ){
int i,m=MAXS-3;
char a[3];
for(i = 0; i < 3;i++)
a[i] = s[i];
for(i=3;s[i]; i++)
s[i-3]=s[i];
for( i = 0; i < 3;i++)
s[m++] = a[i];
}
void main(){
char s[MAXS];
printf("请输入一个字符串:");
gets(s);
Shift(s);
printf("移动后:%s", s);
}

本文介绍了两种将字符串中字符循环左移的方法。方法一通过创建临时数组str1存储前三个字符,然后依次将原字符串后面的字符前移,最后将str1的字符插入到字符串末尾。方法二使用宏定义和额外数组a,同样实现字符串移动。这两种方法都可以有效地改变字符串内容。

被折叠的 条评论
为什么被折叠?



