如何旋转在C给字串的左边还是右边? [英] how to rotate the given string to left or right in C?

查看:104
本文介绍了如何旋转在C给字串的左边还是右边?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C函数由一给定数目的向右或向左旋转的字符串。当一个字符被转动超过结束或取决于方向的字符串的开头,应该环绕

C function to rotate a string by a given number to the right or to the left. When a character is rotated past the end or the beginning of a string depending on the direction, it should wrap around

推荐答案

给出一个字符串 STR 有长度长度和旋转量 N

given a string str which has length length and a rotation amount n

左转相当于

reverse(str, 0, n);
reverse(str, n, length);
reverse(str, 0, length);

向右旋转等同于

reverse(str, 0, length - n);
reverse(str, length - n, length);
reverse(str, 0, length);

现在你只需要一个逆转。

Now you just need a reverse function.

更新:
我想起了你可以如何使用mod的让你始终视的符号旋转​​方向是正确的 N

例如

int mod = n % length;
if (mod != 0) { //if 0, don't rotate
    reverse(str, 0, mod);
    reverse(str, mod, length);
    reverse(str, 0, length);
}

经历的各种情况

如果n == 5和长度= 10,MOD = 5

if n == 5 and length = 10, mod = 5

如果n == 16和长度= 10,MOD = 6 - 16 =向左旋转旋转左6

if n == 16 and length = 10, mod = 6 -- rotating left by 16 = rotating left by 6

如果n == 0和长度=什么,MOD = 0

if n == 0 and length = anything, mod = 0

如果n == -1和长度= 10,MOD = 9 - 1右旋转是一样的9向左转动

if n == -1 and length = 10, mod = 9 -- rotating right by 1 is the same as rotating left by 9

如果n == -15和长度= 9,MOD = 3 - 15右旋转是相同的由3旋转左

if n == -15 and length = 9, mod = 3 -- rotating right by 15 is the same as rotating left by 3

这篇关于如何旋转在C给字串的左边还是右边?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆