Write a C program to rotate the given string.
#include <stdio.h>
#include <string.h>
/* prints characters from str[n] to end of string */
void printChar(char *str, int n) {
int i;
for (i = n; i < strlen(str); i++) {
printf("%c", *(str + i));
}
return;
}
/* prints first n characters in the given string */
void printRev(char *str, int n) {
int i = 0;
while (i <= n) {
printf("%c", *(str + i));
i++;
}
return;
}
#include <string.h>
/* prints characters from str[n] to end of string */
void printChar(char *str, int n) {
int i;
for (i = n; i < strlen(str); i++) {
printf("%c", *(str + i));
}
return;
}
/* prints first n characters in the given string */
void printRev(char *str, int n) {
int i = 0;
while (i <= n) {
printf("%c", *(str + i));
i++;
}
return;
}
int main() {
char rotate[256];
int i;
/* get the input string from the user */
printf("Enter input string to rotate:");
fgets(rotate, 256, stdin);
rotate[strlen(rotate) - 1] = '\0';
printf("Rotating Input String:\n");
/* if the given string has >= 1 character */
if (strlen(rotate) <= 1) {
printf("%s\n", rotate);
return 0;
}
printf("%s\n", rotate);
/* rotate the given string */
for (i = 1; i < strlen(rotate); i++) {
/* prints characters from rotate[i] to end */
printChar(rotate, i);
/* prints characters from rotate[0] to rotate[i-1] */
printRev(rotate, i - 1);
printf("\n");
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter input string to rotate:india
Rotating Input String:
india
ndiai
diain
iaind
aindi
Enter input string to rotate:india
Rotating Input String:
india
ndiai
diain
iaind
aindi
No comments:
Post a Comment