首先把字符串旋转分解成一个一个轮流的移动.
由于这里实现中每次移动会是这样: 比如 src = "abcdefg" 向左移动3位后 就变成了 defgcba, 实际结果是defgabc;
所以才额外添加了一个if 判断语句,用来保证后面的 元素的顺序。
-
char *
-
str_whirl(char *src, int len, int k)
-
{
-
int index_i, index_j, index_x;
-
char tmp, *tmp_dest;
-
-
tmp_dest = src;
-
-
k %= len;
-
-
if(src == NULL || k == 0)
-
return tmp_dest;
-
-
index_j = 1;
-
while(k)
-
{
-
for(index_i = 0; index_i < len - index_j; index_i++)
-
{
-
tmp = src[index_i];
-
src[index_i] = src[index_i+1];
-
src[index_i+1] = tmp;
-
if(index_j > 1 && index_i == len - index_j -1)
-
{
-
-
for(index_x = index_i + 1; index_x < len - 1; index_x++)
-
{
-
tmp = src[index_x];
-
src[index_x] = src[index_x+1];
-
src[index_x + 1] = tmp;
-
}
-
}
-
-
}
-
-
k--;
-
index_j++;
-
}
-
-
return tmp_dest;
-
}
-
-
int
-
main(int argc, char *argv[])
-
{
-
char src[10] = "3abcdefg12";
-
-
char *tmp;
-
printf("the src before -> %s\n", src);
-
tmp = str_whirl(src, 10, 3);
-
-
printf("\tsrc = %s\n", src);
-
printf("\ttmp = %s\n", tmp);
-
-
return;
-
}
阅读(1012) | 评论(0) | 转发(0) |