Blogware Logo
Blogware
Home
Celebriware
Feedback
Need Help?
ImageSurajit Nandy
Published on : 4th Oct 2021
Cover Image
Rotate a string in C programming
Source code :
#include <stdio.h> void swap(char *str, int i, int j) { char temp = str[i]; str[i] = str[j]; str[j] = temp; } void rotate(char *str, int n) { int i; for(i=0; i<n/2; i++) { swap(str, i, n-1-i); } } int main(int argc, char** argv) { char str[1000]; printf("Enter a string: "); scanf("%[^\n]s", str); /*[^\n] tells scanf() function that receives a string until a new line occurs. */ int i = 0; while(str[i] != '\0') { i++; } printf("Original string = %s\n", str); rotate(str, i); printf("Reversed string = %s\n", str); return 0; }
Output :
Enter a string: Surajit Nandy Original string = Surajit Nandy Reversed string = ydnaN tijaruS
Explanation : Have you noticed how we have taken input? [^\n] tells scanf() function that receives a string until a new line occurs. Then, we have calculated the length of the string. After that, from middle of the string we have swapped the characters.
CelebriwareProductsServicesAdvertisementInvestorsPrivacy PolicyTerms of Service
Blogware Logo
Copyright © 2025 Blogware. All rights reserved.