Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

how to rotate the given string to left or right in 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

rotate left is equivalent to

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

rotate right is equivalent to

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

Now you just need a reverse function.

Update: I thought of how you can use mod's to make you always rotate in the right direction depending on the sign of n.

e.g.

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

going through the various cases

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

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

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...